Тёмный

React Query: Fetch, cache, and update server data using queries and mutations | ReactJS Tutorial 

Marius Espejo
Подписаться 28 тыс.
Просмотров 55 тыс.
50% 1

In this video we discuss introducing React Query to a ReactJS application. React Query provides a hooks API which allows you to fetch, cache, and update data. At first glance it seems like just a simple library, however you'll find out that it is packed with features which pretty much handle most of the server state management concerns that you might have in any client application. This includes things like automatically de-duping requests, background refreshing, caching, optimistic updating, accessing data globally and several others.
If you make React Query manage your server state, you'll find that the remaining client state that requires management becomes VERY small and likely will remove the need for more complex solutions like Redux. This is state management solution that you absolutely should know about if you're a React developer!
00:00 - Intro
00:25 - Why you need React Query
02:08 - What we're going to build in this tutorial
03:15 - Using axios to define our reusable API methods
05:09 - Setting up the QueryClient and Devtools
07:10 - Intro to fetching data with the useQuery hook
10:06 - Utilizing loading states
11:21 - Catching errors and basic error handling
21:05 - Important defaults to know about
21:26 - Auto Caching and garbage collection
22:44 - Auto background data refetching/refreshing
30:00 - Using mutations and the useMutation hook to update data
33:56 - Invalidating data in the cache (trigger refresh)
36:44 - Optimistic updates
39:58 - Updating the cached data using the response data
42:55 - Looking at what else React Query provides
43:36 - Conclusion: Discuss the point of React Query and if you still need things like Redux
45:23 - Outro

Опубликовано:

 

29 июн 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 154   
@shivrajnag12
@shivrajnag12 2 года назад
To learn/use react-query. Key-points to remember 1) Read about very imp topics like Important Defaults, Optimistic Update in react-query doc 2) Monitor your Network calls in Network tabs in Dev Tools. Make sure you are making API calls according to your need, because react-query comes with some default settings which you might not want and you can always override it. Throttle your network speed to see different scenarios.
@anthonymarquez2542
@anthonymarquez2542 2 года назад
I wish I had found this video a few months ago. You’re really clear at explaining this and have everything laid out accordingly. Thank you for this!
@mariusespejo
@mariusespejo 2 года назад
I’m glad it’s helpful! Thanks for stopping by to comment Anthony 😄
@kevingalvez9126
@kevingalvez9126 2 года назад
I really appreciate how you presented react-query, it was clearly explained as it was being coded. I'm currently learning this package for work and your tutorial was very timely. I also see a tutorial for NestJs--TypeScript, which I'm excited to learn! Subbed!
@mariusespejo
@mariusespejo 2 года назад
Thank you! Glad you subbed, I actually have a lot more frontend/react content I’d like to make, if you’ve got ideas let me know!
@EliZevin
@EliZevin Год назад
I appreciate how clear and understandable your explanation is
@ytlagu2010
@ytlagu2010 3 года назад
got knowledge that I have been looking for over 3 years, I am talking about handling the "U" in CRUD operation. Thanks Marius!!! Great video...
@mariusespejo
@mariusespejo 3 года назад
awesome! glad I could help
@beorntwit711
@beorntwit711 2 года назад
My man, you're quickly becoming my goto teacher for more modern JS web dev stuff. Your topic choices are on point, and the presentation is great.
@mariusespejo
@mariusespejo 2 года назад
Glad you think so Branimir! Thanks for your feedback 🙏
@namesurname7179
@namesurname7179 2 года назад
Best react-query explanation, thanks a lot
@StephenMcMahon
@StephenMcMahon 3 года назад
Thanks for another great lesson, Marius. I've recently passed several of your videos on to my colleagues.
@mariusespejo
@mariusespejo 3 года назад
thanks for sharing Stephen! glad the content is useful
@sh3lol520
@sh3lol520 Год назад
the best tutorial on useQuery, it was such a confusing topic for me. But now super clear!
@mahmudulmurad
@mahmudulmurad 2 года назад
wow, best react-query explanation, thanks a lot man. This was just perfect as i expected. you covered the most important edge cases which may take lot of time in the first place if someone didn't know. Best of luck man.
@mariusespejo
@mariusespejo 2 года назад
Thanks! Glad it was helpful for you
@kenbinta2246
@kenbinta2246 2 года назад
10/10 . Well explained, straight to the point. Thanks for this tutorial, I found it really helpful.
@F2H16
@F2H16 Год назад
Thanks Dude, it has really been a great walk through. I have applied it at work today.Keep it up.
@_tonygaeta
@_tonygaeta 2 года назад
Wow! Great video. You’re a really good teacher. I needed to learn react-query as part of a take home interview test.
@mariusespejo
@mariusespejo 2 года назад
Thanks Tony! Hope the interview goes well for ya, good luck!
@andregomes7232
@andregomes7232 Год назад
That’s an amazing content bro. You made it look like easy! Thanks a lot
@stanleychukwu7424
@stanleychukwu7424 3 года назад
thanks, i just finished the video, and i learnt alot! thank you bro!
@rp2804
@rp2804 Год назад
Man, you deserve a big thanks!
@jaqp911
@jaqp911 3 года назад
Really good !! I loved this video, I have learn a lot, more than I could do alone
@mariusespejo
@mariusespejo 3 года назад
i’m glad, thanks for your feedback!
@amisoliman123
@amisoliman123 2 года назад
Thanks Marius, your video helped me understand this very well :)
@pranavyeole102
@pranavyeole102 2 года назад
Thanks for the video ❤️ Great stuff!
@logistics_guy
@logistics_guy 2 года назад
Good stuffs. I really like the way you present, which is to focus on the points.
@mariusespejo
@mariusespejo 2 года назад
thanks for your feedback!
@mikemontgomery8313
@mikemontgomery8313 Год назад
Great explanation. Ive had a hard time getting my head around this new server cache management abstraction.
@nishanthakumara8753
@nishanthakumara8753 2 года назад
Awesome explanation. Thank you for this
@samuelcouillard4229
@samuelcouillard4229 2 года назад
Thank you so much. This is the best Query tutorial I have seen so far - most of them seem to obviate the useMutation for some reason.
@mariusespejo
@mariusespejo 2 года назад
Glad you found it useful!
@anoopvasudevan
@anoopvasudevan 3 года назад
hey, thanks for this. Neatly explained and good presentation. Liked the part where you explained the default cache time. Could have covered the stale time as well along with that.
@mariusespejo
@mariusespejo 3 года назад
Thanks for your feedback! That’s true I think I should have covered stale time a bit more. It’s something that could be confusing to some because cached data is immediately “stale” by default. Perhaps I will cover that more in a follow up video, since there are also quite a bit more topics to cover that I left out in this intro.
@amilrustamov3643
@amilrustamov3643 2 года назад
Thanks for great lesson , i was looking for video lessons about react query ,finally i found .Thank you very much
@mariusespejo
@mariusespejo 2 года назад
You’re welcome Amil, glad you found what you’re looking for!
@artsandyangelobertabing1572
@artsandyangelobertabing1572 2 года назад
its well explained thank you for your effort, every details are explained
@winafiuu
@winafiuu 2 года назад
You could name this video to 'No bullshit guide to React-Query'. The video was on point! Many many thanks! Just love your content.
@mariusespejo
@mariusespejo 2 года назад
haha thank you! I try my best not to ramble too much and just get into things
@mateusmn
@mateusmn Год назад
Thank you so much for this class
@gilliland1984
@gilliland1984 2 года назад
This is excellent. Thanks!
@pravinkumar-lz2jm
@pravinkumar-lz2jm 2 года назад
Really good quality content bro. thanks
@yishanlu3644
@yishanlu3644 2 года назад
Best react query video ever!
@mariusespejo
@mariusespejo 2 года назад
Thanks glad you think so 😄
@quachhengtony7651
@quachhengtony7651 2 года назад
That background refetching is insane
@Shebu
@Shebu 2 года назад
Great video and explanation.
@abdoshaibany
@abdoshaibany 2 года назад
That was a good explanation .. Thanks a lot
@AnsgarSteinkamp
@AnsgarSteinkamp 2 года назад
React Query is great, and this tutorial is even greater! Thank you very much, Marius! PS: For an extended version of this tutorial, I'd recommend the Udemy-course of Bonnie Schulkin, which is really excellent, too.
@mariusespejo
@mariusespejo 2 года назад
Glad you think so, thank you Ansgar!
2 года назад
Hi, does it cover react query V3 or V2???
@AnsgarSteinkamp
@AnsgarSteinkamp 2 года назад
@ Both V3. The one of Bonnie Schulkin and this one.
@rockNbrain
@rockNbrain 2 года назад
Great job! TKS
@MaybeBL1TZ
@MaybeBL1TZ 2 года назад
soo i switch my project from node to nestjs because of you now i might also switch to react-query you are amazing my friend
@mariusespejo
@mariusespejo 2 года назад
Awesome, glad those are working out for you!
@juanignacio383
@juanignacio383 Год назад
Handling the errors would be amazing
@regieaveros6525
@regieaveros6525 3 года назад
it saves my day :)
@ArunKumar-dd3vk
@ArunKumar-dd3vk 3 года назад
The bestt 🔥
@balimuttajjofrancis1002
@balimuttajjofrancis1002 2 года назад
good introduction to rquerry
@amixengineer
@amixengineer 2 года назад
great introduction I liked it.
@mariusespejo
@mariusespejo 2 года назад
Thanks!
@agustinperez8700
@agustinperez8700 2 года назад
aweasome !
@cu48
@cu48 3 года назад
I was confused to use react-query with document. because I am not good at English. your lesson is very helpful.
@omkarkulkarni3644
@omkarkulkarni3644 3 года назад
You got a subscriber ! Thanks
@mariusespejo
@mariusespejo 3 года назад
thanks! what types of content are you looking for? mostly react stuff?
@amirhoseinzare1592
@amirhoseinzare1592 Год назад
wonderful
@yanhaixiang
@yanhaixiang 2 года назад
Love your videos! What softwares/tools do you use for the videos? Hopefully someday I could make tutorials like you do ^^
@mariusespejo
@mariusespejo 2 года назад
You mostly need something to do screen recording and something to then edit it. On mac for example you literally can get started for free with quicktime and iMovie. You can also use OBS I think for screen recording and use anything else for editing, e.g. davinci resolve is free but you can use whatever.. to get started with editing all you really need to know is how to trim down what your recorded and stitch segments together, that’s honestly 90% of the work. Only other thing I suggest is get a decent mic, I would suggest start with a usb mic, don’t over spend on gear until you know you’re dedicated to making more content. If you’re interested I highly suggest just getting started, start somewhere on any topic, don’t worry about the views. I personally hesitated for a long time and wish I started years ago
@abhinavsingh-zc2hk
@abhinavsingh-zc2hk 2 года назад
Amazing tool
@toannew
@toannew 11 месяцев назад
19:30: prevent the api is call before id is available (using OPTIONs) 34:10 update data on Cache after mutating (useQueryClient) 37:30: update data (2nd method) onMutate
@ytbcmt4686
@ytbcmt4686 3 года назад
Respect form India
@suatyargc5738
@suatyargc5738 Год назад
Thanks brother
@tluanga-ruatpuii-pa
@tluanga-ruatpuii-pa 3 года назад
Thank you
@tomo6723
@tomo6723 2 года назад
Thank you for always uploading helpful videos! If you could replace this with typescript, that'd be great!
@mariusespejo
@mariusespejo 2 года назад
It’s honestly fundamentally the same even with typescript, react-query itself is written in typescript so it can plug into a TS react app without really any additional work. There are just a few places where you might need to provide types but for the most part it knows how to figure it out based on what your api request itself returns
@user-dw8lb8lc7u
@user-dw8lb8lc7u 3 года назад
hi from Russia! your lessons very cool, espessialy nest+grapql video
@mariusespejo
@mariusespejo 3 года назад
hello and thank you! glad you are finding content useful
@nosirovbehzodjon
@nosirovbehzodjon 2 года назад
thaks
@toddcagelives
@toddcagelives 3 года назад
GOOD
2 года назад
Thanks for your video. If you have time and if you want would you mind to explain us what's the difference between mutate and mutateAsync please ? There are both async function so I just don't get when I'm suppose to use mutate instead of mutateasync
@mariusespejo
@mariusespejo 2 года назад
Good question.. you can think of it as basically equivalent to the regular mutate, except mutateAsync returns a promise so you can await it and trigger behaviors after the mutation, sort of similar to what you might do in onSuccess/onSettled … e.g. await mutate(); doSomethingAfterMutationComplete();
@azula9714
@azula9714 3 года назад
Hi, great explanation. Also Im interested to know whats your VSCode theme & font syle. Thanks
@mariusespejo
@mariusespejo 3 года назад
I believe I’m using github dark here, I just switch it up once in a while. Font is just default
@thangta8147
@thangta8147 Год назад
good
@josuebarros5727
@josuebarros5727 2 года назад
Where can we get the repository of this cool video?
@akashshrestha01
@akashshrestha01 2 года назад
would love to see on rtk query too
@mariusespejo
@mariusespejo 2 года назад
Yeah I’m actually interested in doing a comparison with it
@linmus2370
@linmus2370 2 года назад
Freaking awesome! Where are u from? -
@vicentemanriquez5166
@vicentemanriquez5166 2 года назад
What theme of vs code do you use ? Nice video btw
@mariusespejo
@mariusespejo 2 года назад
night owl in this one
@oyerohabib
@oyerohabib Год назад
Hi Marius, thanks for the great resource. I am currently watching the video as a code along but I don't know how to get the reference to the localhost:3001 you used for the server-side. Is it deployed anywhere for use, or how do I make use of that thank you.
@mariusespejo
@mariusespejo Год назад
That was just a basic CRUD api I happened to have from a previous video, however you can use any CRUD example (either your own or a public API that you can find). For example you can use jsonplaceholder.typicode.com/ which has a mock API that you can do CRUD against
@oyerohabib
@oyerohabib Год назад
@@mariusespejo Thank you very much for the response, highly appreciated. I am trying that out.
@cryptodev2615
@cryptodev2615 2 года назад
I really like how your using best practices here. I think I have done things the easier, beginner friendly for too long. Specifically separating API calls from your React code. I have a question though! At 4:00, you export default the getUser fn but not the getUsers fn. Why!? Secondly, in the getUser fn, why did you wrap res in parentheses!? Ex. (res) but not in getUsers fn? Thanks ahead, appreciate anyone's help
@mariusespejo
@mariusespejo 2 года назад
Good eye! The getUser not being exported at 4:00 was a mistake, but you’ll notice that’s corrected at 17:45 I might have just not remembered to mention that. As for the parentheses… no reason, don’t get too hung up on that. They’re basically the same. Typically I’d probably have prettier to make that automatically consistently formatted for me. Anyways sometimes you make tiny inconsistencies when you type haha as long as you understand that a single parameter arrow function can be written as (arg) => { } OR arg => { } then there shouldn’t be any real difference or problems. It’s only until you have more than one parameter that you’re enforced to use parentheses. It’s important to have enough language fundamentals so that you understand those shorthands. You should also know that if I didn’t export getUser then I wouldn’t have been able to use it, so you’d likely be able to guess that at some point in the video that likely was corrected if I ever had to invoke it. Anyways great attention to detail!
@exponent42
@exponent42 3 года назад
what if you wanted to share UserDetails for selected user app-wide, would you pass this information into useContext API, or doesn't react-query replace needing context?? thanks again
@mariusespejo
@mariusespejo 3 года назад
good question, the query cache effectively replaces need to put things in your own context. E.g you could query the user high enough in your component tree, perhaps in the root component itself. And that would effectively make the user basically global, and other component rendered below that root can simply pull the user data out of the query cache (which itself functions like context which you can access anywhere since the provider for it wraps your entire app)
@exponent42
@exponent42 3 года назад
@@mariusespejo thanks so much Marius this is extremely helpful and saves so much time not having to mess around with useContext and useReducer
@madtin
@madtin 2 года назад
you can just store the selected user id and fetch it with useQuery on the component you need
@ARundyAlton
@ARundyAlton 2 года назад
whats the ? before data doing and is thbase /users get request async and how is that addressed?
@mariusespejo
@mariusespejo 2 года назад
That question mark is the optional chaining operator, I recommend reading about it if you’re not familiar. All api requests are effectively async, it’s addressed just like how you would handle any promise. A huge point about this video is that react-query takes care of handling that for you along with managing the state
@6abriel9
@6abriel9 2 года назад
awseome video dude, I have a problem, why it returns this error: "Missing queryFn" and 401 not authorized? I'm using jwt..
@mariusespejo
@mariusespejo 2 года назад
sounds like you didn’t provide the query function correctly. double check your syntax. As for the 401, well that means you’re not attaching the jwt to the auth header correctly. That doesn’t really have anything to do with react-query but more on your underlying request
@6abriel9
@6abriel9 2 года назад
@@mariusespejo thanks for the answer, i was forgetting the arrow function in the axios get, LOL
@mariusespejo
@mariusespejo 2 года назад
haha glad you figured it out!
@abinayaabi5604
@abinayaabi5604 2 года назад
Wonderful,Where I get the code?
@sergioddh
@sergioddh Год назад
How can I update a list when editing a line? I get the row data but the PUT method returns only the updated row, how do I make the list be updated using setQuery and not using invalidateQueries?
@mariusespejo
@mariusespejo Год назад
Assuming you’re doing your PUT within a mutation, then you can do optimistic updates, see: react-query-v2.tanstack.com/guides/optimistic-updates Which is basically what you’re attempting, get the response data back of the edit and explicitly setQueryData to update the global cache
@sergioddh
@sergioddh Год назад
@@mariusespejo yes! It was exactly what I did! Thanks a lot!
@hyggedev2124
@hyggedev2124 Год назад
Hey awesome tutorial. I finally made the decision that I should essentially be using react-query for literally every single project. I have a question though. For anyone maybe reading this lol. Why is it when I have a "isLoading" if check, that my entire application just goes blank on a throttled connect? I have the isLoading state returning before the UI is returned too, just like your example, just like the example from the docs. I can't figure it out. Any help would be appreciate D:
@mariusespejo
@mariusespejo Год назад
Hmm not sure, are you positive the thing you’re returning isn’t maybe causing errors?
@hyggedev2124
@hyggedev2124 Год назад
@@mariusespejoSorry forgot to check this. Yeah as I was watching your tutorial and applying it to my app, it wasn't working properly cos I was setting local state with the data response. Can't do that. It also defeats the purpose as react-query can't cache the results if you set local state! But once I realized all was good 👍
@ddikodroid
@ddikodroid 2 года назад
Hi Marius, how about infinite scroll with react-query?
@mariusespejo
@mariusespejo 2 года назад
Yup react-query has support for that
@electroheadfx
@electroheadfx 3 года назад
amazing, do you have a github from the code repo ? thanks
@mariusespejo
@mariusespejo 3 года назад
not at this time sorry
@electroheadfx
@electroheadfx 3 года назад
@@mariusespejo no problem, thanks
@aadarshaacharya267
@aadarshaacharya267 2 года назад
can i get the server-side code?
@GamingYT-cf3be
@GamingYT-cf3be 2 года назад
Can with do it with reddit API? Because in reddit API pagination working on after before method in URL please suggest how to do infinite scroll with reddit API.
@mariusespejo
@mariusespejo 2 года назад
React-query has support for infinite scroll and pagination if you check the docs
@GamingYT-cf3be
@GamingYT-cf3be 2 года назад
@@mariusespejo yes I know but the tricky part in react API is managing the index [after, before] , you need to get the last array index in parallelly with API response.
@iamchid
@iamchid 2 года назад
Does redux is not needed, if we use react-wquery?
@mariusespejo
@mariusespejo 2 года назад
It’s overkill if you’re already using react-query. I would suggest a simpler library for client state like zustand
@darama4237
@darama4237 Год назад
pleasse tell me how to add users?
@khoroshoigra8388
@khoroshoigra8388 2 года назад
Pwede kaya ang redux-toolkit + react-query ??
@mariusespejo
@mariusespejo 2 года назад
If you’re already using redux toolkit you’re better off using RTK Query: redux-toolkit.js.org/rtk-query/overview
@khoroshoigra8388
@khoroshoigra8388 2 года назад
@@mariusespejo ahh ok po, thanks sir
@vansonnguyen4107
@vansonnguyen4107 2 года назад
What are differences with the real-time app? Can you tell me?
@mariusespejo
@mariusespejo 2 года назад
what real-time app?
@vansonnguyen4107
@vansonnguyen4107 2 года назад
@@mariusespejo Realtime web application like signalR, WebSocket
@mariusespejo
@mariusespejo 2 года назад
react-query is really better suited for request-based communication, it doesn’t really support real-time connections like with websockets (as far as I can tell)
@mariusespejo
@mariusespejo 2 года назад
real-time apps would usually require some kind of event-based publish/subscribe method, which doesn’t really fit the model that react-query uses which is more towards request/response
@vansonnguyen4107
@vansonnguyen4107 2 года назад
@@mariusespejo Thank you!! Your accent is so good
@rezaulmasum205
@rezaulmasum205 2 года назад
How to send multiple parameters in react query?
@mariusespejo
@mariusespejo 2 года назад
What kind of parameters are referring to? Api/url params are handled by whatever you’re using to make requests e.g. axios/fetch. React-query is simply the state manager
@rezaulmasum205
@rezaulmasum205 2 года назад
@@mariusespejo suppose i would like to pass multiple parameters to my fetcher function. How can I do that?
@Shin-jj3qt
@Shin-jj3qt 2 года назад
Hi Marius! May I ask, are you a Filipino?
@mariusespejo
@mariusespejo 2 года назад
Opo! 🇵🇭💪
@Shin-jj3qt
@Shin-jj3qt 2 года назад
Yooown. Astig!
@akilashalini1470
@akilashalini1470 Год назад
Can I get the code ?
@drakephillips7613
@drakephillips7613 3 года назад
can I replace react apollo with react query?
@mariusespejo
@mariusespejo 3 года назад
you can use it with graphql if you’d like: react-query.tanstack.com/graphql it more depends on if the feature set of react query is good enough for you to remove apollo.
@drakephillips7613
@drakephillips7613 3 года назад
@@mariusespejo I see. Apollo pretty much has everything I need and even more. That's the case, it adds a lot of overhead so I was looking for a simpler solution. There's urql too. But react query looks pretty nice as well. Thanks for the reply mate. Big fan of your work.
@mariusespejo
@mariusespejo 3 года назад
thanks Drake! I have tried urql myself, I would personally recommend that over apollo if you specifically want something for graphql that’s lighter weight. The only thing I saw that apollo did differently was their client state manager but there are better solutions for that like zustand in my opinion
@drakephillips7613
@drakephillips7613 3 года назад
@@mariusespejo Thanks for letting me know about zustand. Yeh, I agree with you on urql. I looked into react query and I'm gonna use it for my next project instead of apollo. I've been using graphQ codegen for types anyway so it fits perfectly.
@ahmaat19
@ahmaat19 3 года назад
Who decided to migrate react-query from the redux/redux toolkit?
@mariusespejo
@mariusespejo 3 года назад
those are technically two separate packages for different problems. You can use both if you’d like. If you add in react-query it will definitely reduce the need for redux to manage your server data though (potentially making your overall redux code simpler)
@boot-strapper
@boot-strapper 3 года назад
auto retries seems like a bad idea. Some errors, such as 409 should not be retried.
@mariusespejo
@mariusespejo 3 года назад
depends on the use case, if it manages to succeed in getting a response for the user then the user will only see a loading screen and not an error page. That’s useful in some cases like maybe a user momentarily loses internet connection. But yeah I sort of think of it as just a delay in showing the error, definitely not always necessary. Good thing you can turn it off though. Probably one of the things I wish wasn’t a default
@Pareshbpatel
@Pareshbpatel Год назад
{2022-11-26}
@Rxlochan
@Rxlochan 3 года назад
Mumbo Dumbo 😂😂
@mariusespejo
@mariusespejo 3 года назад
yeah I need to work on more creative examples hahah
@EliZevin
@EliZevin Год назад
I appreciate how clear and understandable your explanation is
Далее
Five Clever Hacks for React-Query and SWR
40:09
Просмотров 58 тыс.
React Query en 40 minutes - Cours complet débutant
40:04
The last one surprised me! 👀 🎈
00:30
Просмотров 2,3 млн
Découverte de react-query
45:55
Просмотров 26 тыс.
TypeORM v0.3.x Migrations, queries, with NestJS!
28:37
Redux Toolkit Query vs React Query
22:12
Просмотров 104 тыс.
What Next.js doesn't tell you about caching...
13:32
Просмотров 10 тыс.
System Design has never been easier
14:26
Просмотров 112 тыс.