When you use React Query, achieving caching and optimistic updates becomes very easy, and as a result, your app feels fast. By using a stale time, you can reduce network requests if your data doesn't change frequently... I personally love react query.
@@freezzefx2670 No, you don't have to use any other state management library along with React Query. React Query handles its own states, and you can access different state values by destructuring them like this: const { data, isLoading, isError } = useQuery('myQueryKey', fetchDataFunction); It is like this: Initially, when your component mounts, isLoading becomes true. So, while fetching data, you can show a loading indicator. If something goes wrong, isError will become true, allowing you to show a different UI for errors. Once data comes in, it will be available in data, and you can use that data to show your actual UI. All these are states, so as they change, your component will rerender automatically. I have destructured only three properties (data, isLoading, isError), but there are many other properties that you can use; refer to the docs.
@@freezzefx2670 No, you don't have to use any other state management library along with React Query. React Query handles its own states, and you can access different state values by destructuring them like this: const { data, isLoading, isError } = useQuery('myQueryKey', fetchDataFunction); It is like this: Initially, when your component mounts, isLoading becomes true. So, while fetching data, you can show a loading indicator. If something goes wrong, isError will become true, allowing you to show a different UI for errors. Once data comes in, it will be available in data, and you can use that data to show your actual UI. All these are states, so as they change, your component will rerender automatically. I have destructured only three properties (data, isLoading, isError), but there are many other properties that you can use. refer to the docs.
@@freezzefx2670 No, you don't have to use any other state management library along with React Query. React Query handles its own states, and you can access different state values by destructuring them like this: "const { data, isLoading, isError } = useQuery('myQueryKey', fetchDataFunction)" It is like this: Initially, when your component mounts, isLoading becomes true. So, while fetching data, you can show a loading indicator. If something goes wrong, isError will become true, allowing you to show a different UI for errors. Once data comes in, it will be available in data, and you can use that data to show your actual UI. All these are states, so as they change, your component will rerender automatically. I have destructured only three properties (data, isLoading, isError), but there are many other properties that you can use; refer to the docs.
@@freezzefx2670 No, you don't have to use any other state management library along with React Query. React Query handles its own states, and you can access different state values by destructuring them. Unfortunately, I can't provide a code example here because RUclips removes my comment if I do so. It is like this: Initially, when your component mounts, isLoading becomes true. So, while fetching data, you can show a loading indicator. If something goes wrong, isError will become true, allowing you to show a different UI for errors. Once data comes in, it will be available in data, and you can use that data to show your actual UI. All these are states, so as they change, your component will rerender automatically. I have destructured only three properties (data, isLoading, isError), but there are many other properties that you can use; refer to the docs.
The draw to start using react-query was essentially I could completely isolate components with it’s data fetching, and when another component tries to fetch the same data it’s smart enough to only send one request. It makes moving around components in different ui’s great, because the data logic is also encapsulated.
I did this via simple events and a hook and packaged it as react-state-events. indeed moving components around is now really easy and the code redesign was also very very simple in an existing project.
Totally agree. I am currently working in 2 projects in my company. One with redux as global store and the other with react-query. The main problem I face while using redux would be the caching and loading state. When things get complicated and you have to make 3-4 dispatch calls in a function, then maintaining the loading state with redux becomes very difficult. Also the isLoading and isFetching in react query can be very handy, showing different loaders at different instances in an app. Another niche case with react query is that when you want to cancel pending queries on unmount of a component, it can be achieved by just passing the abort signal at the right place. PS: Left out a major thing, in instances when you're firing a post request, you can invalidate the get query and it cleans the cache, which will require additional lines of code at numerous places (depending on your application) while using redux.
@liftwithamey all the api responses are cached in react query based on the query key. So if you set refetch on mount to false, it will use the cached data which is basically useSelector in case of redux.
@@ssk7690I just took out logic out of UI code and everything became very obvious. Now a regular JS class tells React what to do through events and React updates accordingly. I can get as async and complex as I want and the UI code stays very simple and readable. Caching? I'll just stash it in the controller. Need a sequence of requests? just regular async/await does it, then publish success or failure accordingly. Cancels? push/pull a list of them in the controller. React doesn't need to know about that.
@@MadsterV by cancelling pending queries I meant something else. Let’s see this with an example. Say you’re firing 10 api calls on a page. Now if the user clicks on a different tab within the page, by default the api calls in second page wouldn’t start until the previous 10 are completed. Hence the need to cancel the pending queries based on user activity. This can be achieved very easily using react query, all you’ll need is the query key.
As long as you use the react query in component / customhook it's fine. The last issue I have faced is query on click... and yeah someone of you may say "hey there is simple 'refetch' method" but well it's not that easy: 1. query function is a hook so I cannot use it simply like: if args is passed then fetch the query -> you have to wrap it in additional components/ wrapper 2. refetch method is not using the data stored in react-query context e.g. 1. manually query ('refetch') was about "dogs", 2. was about "cats", 3. was about "dogs". Suprise even the data was already in context the api call has been invoked. for me RTK query is much better ;)
react-query still using useEffect under the hood, everything is based on the specific use case. also there are other libraries like RTK that provide similar functionalities.
and ??? it uses a mixture of useEffect and useSyncExternalStore so what? the only time i don't see react-query necessary is when (no framework obv) - you need to do pooling quickly for one thing .. and planning later on to use Websocket/SSE
Great point that react-query isn't a fetching library,, but an async state management library (tanner should look into rebranding away from the phrase "query" then). Instead of the common question ppl ask "do I need react-query if I'm already using server components", think you can help explain when we need client side fetching when we already have fetching server side
React query rocks, even for use cases where using ssr and rsc. Major kudos and thanks to team tanstack. There’s also rtk query, which I like/prefer in some ways, but react query nails all the use cases like handling ssr and infinite query. I can’t imagine handling async state using use effect- my gawd.
@@smithrockford-dv1nb you're thinking of SWC (speedy web compiler). SWR is a cache invalidation strategy (stale while revalidate). I believe it's also a useQuery-like library from vercel.
@@smithrockford-dv1nb You're confusing it with SWC. SWR is a library by Vercel to do the same thing, though more opinionated focused on data fetching than general async, hence its name (Stale While Revalidate).
You also could add an AbortController and pass the signal to fetch as a prop so that when the useEffect cleans up, it can abort the query so that the browser and backend dont need to keep processing the request.
Surprised you don't use query key factories in your code, this is something I learned from Tkdodo's blog and its been amazing because now I don't have to remember query key names if I want to invalidate them in any place.
Ha. I've been saying "Tanstack Query is an async state management library" for ages and at the start, I was trying to figure out why I agreed with you because I can't recall watching anything of yours about Tanstack Query. It's because I watched that exact Jason Lengstorf podcast vod when I was learning about tanstack query.
It's slightly easier to handle (no need to do QueryClientProvider/useQueryClient) thing, it's 3 times lighter according to bundlephobia APIs for cases Theo mentions are the same, the code from this video would work with useSWR exactly the same Because of worse docs, i had problems making useSWR and Tanstack Table to cooperate (i guess Tanstack tried to vendor lock-in to sway me to use Tanstack/React Query) but i overcame it
2:49 yeah that’s a bug but you don’t need a library to fix that bug, use an abort controller and abort inside your returned useEffect clean up function.
This is also a large bit of what HTMX does for you that fetch does not do, hx-sync is absolutely amazing from a state management point of view and fits in perfectly and is a very good example of why declarative fetching at the core of the framework is so much better than imperative fetching in javascript
What about primitive obsession? I like react-query but I am wondering if there is a way to use it together with state machine for use cases where you have some form, some loading state, possible error state, confirmation of request send state and so on. I would like to use it in state machine, not always check if I have data or error
absolutely. react-query expects a rather specific use case and once you step out of it, you're on your own. I moved logic out of React code into a regular JS controller class and just use a simple pub/sub to communicate events from the controller to the UI through a subscription hook (react-state-events). Then everything clicked without the need for awkward hooks and rendering weirdness (I did use a very simple state machine!). Controller offers methods which are hooked to UI controls and UI updates as needed when the controller decides to do so. I can even call the controllers from other components if I wish to do so. I can unmount and keep the controller alive to remount UI later, in a different place or even mount many different components at the same time that render the same data in different ways. Very flexible with minimal boilerplate! No useEffect, no double calls, no undesired renders. Just a plain class sending UI events and a plain React component rendering whatever the events say.
Nice video Theo. This is what pisses me off sooooo much about React coming from Svelte, these one-off packages that are required to do basic stuff the framework should be providing a solution for (IMHO)
I used to feel this way more, but then I had to do long-term maintenance on some Angular apps? I started to much prefer a more modular approach. I think the reality is that the "official" version would work half as well and would reduce the support given to alternatives. At the very least, there's tradeoffs.
@@Nassifeh This is actually a pretty good point I can see where you’re coming from. I’ll probably feel less salty once I get better at using these 3rd party react packages
@@MerkieAE It's definitely an adjustment period, even if I'm in favor of it. 😩 I miss when every guide or tutorial was doing stuff the same way I am. But I won't miss having to update basically the whole app all at once twice a year.
I love react-query and go with all of our arguments. I see problems with useEffect elsewhere though. It's used when reducers should be employed. I build complex CMS where you have loads of changees to the client state of the object fetched and eventually saved to the server. Saw people jerking useState and useEffect to manage that. All removed by simple useReducer or redux with some thunks from time to time. I think as state manager, when you do many updates to the client state (like in my case) keeping things out of the react-query and in reducers is simpler, especially if you don't want to run into key management hell. Compared to your example for non-fetch examples, it may be why reducers work better in that case is that structure of my model is unpredictable and can be deeply nested.
Yeah. If you use optimistic updates so much that your data is basically just state, with an extra database synchronization step, you should embrace a state manager for it, not a query manager.
React Query Doesn't work really well with server components. Nextjs fetching api comes with caching, revalidation already so react query is not really necessary
The article states that the custom fetch hook is spaghetti code, like what do you think is going on in React Query behind the scenes? black magic? Before React Query came along every senior dev would create their own query custom hook, and that's the thing the team at Tanstack did, they just turned into a library and added a ton more of functionality. If you just need to make simple requests, making a good custom fetch hook is a good solution, React Query didn't invent data fetching and it shouldn't be imposed as the only solution.
I'm new to react. Why do we need to do useEffect just to populate a form? For example... ``` const MyFormComponent = ({ selectOptions }) => { const [options, setOptions] = useState(selectOptions); return (
hey man, I watched your videos a lot but I never subscribe. 🤣 but when you show your cat at the end of the video 🤩 aww so cute I need to click subscribe now.
my guesses for the 5 potential bugs: - out of order responses when category changes - data and error set simultaneously, not properly overriding both values when category changes - stale result being used when category changes - not properly accounting for bad status code (that depends on the api really) - cannot determine loading state because of default data empty array value - fetching not cancelled when component unloaded
I also use it but I still do not know why they don't have an own fetch function, you still have to change the default behavior of fetch to make it fully correcttly working with react query
If the core methods are so perilous, it seems like the argument could be made that this should be in the core framework. The API should be improved so that the right way is the easy and obvious way, yes?
I'm doing something at work at the moment with Launch Darkly (feature flagging tool). Whenever the user changes, we tell launch darkly, and that gives us updated feature flags based on the data sent. In order to access the flags we have to use their client to fetch them. These flags need to fetched asynchronously however they are already cached in the launch darkly client. I ended up just fetching the flags and dispatching to redux whenever we change the user so the UI is always in sync but I'm still debating in my mind whether I should have used React Query... This is React Native btw. Do you have any thoughts on this?
50-50 here. We used it for a medium project and in some cases we didn't like some of the workarounds and React Query way of doing things. It is a library from another author on how they believe data fetching should be handled, and I respect their opinions, but it is not one stop solution for everything. Not a bad experience, but not an amazing as well. Nevertheless, I have to give credit for an amazing library as a feat in developing it.
I've done CRUD cache engine from the url structure and also doing optimistic CRUD changes (as part of the cache engine) after successful mutations.... Helps me to minimize the codebase, instead of thousand custom hooks files....
My chest started to tighten right at the end of bug #4. I only used react recently and and I made the jump to react query when the mvp got to paid stage, and I am proud to say that I am never going back. 🎉
In my every-day job my team uses redux-saga to achieve pretty much the same thing react-query does: async state management. That said, what are the differences between these two libraries? Is one better than the other? Or everything resolves in “it’s your preference”? Great video btw!
You probally use sagas "wrong" way. React-Query is 90% same things compared to Redux Toolkit Query - which is solve the 'fetch data' use-case of sagas. If your daily sagas purpose is :fetch data, update loading, set success, set error, invalidate incomming fetching action, wait another action's data , your work is just overlapping RTKQ - as I said "wrong". I personally though sagas make no sense to my project since RtkQ released. Back from start, sagas CAN handles all React-Query usages - but in a dirty way
so whenever we need to fetch some data from API or to get async data, then we use react query instead of useEffect(), Then when is good idea to use useEffect()? do we still need it?
SWR is a decent way to cache fetch calls. React Query is a groundbreaking way to manage async functions and state in React. IMO, they’re about as comparable as a toy car and a semi truck
React Query is data agnostic, meaning it doesn't care how you provide it the data, via fetch, via XMLHTTTRequest, via axios or pull it from localStorage. All it cares about is that you give it a function that returns some data or throws an error. If the function returns the data it is considers a success, if it throws it is considered an error.
If someone is already using redux toolkit for managing states what would you suggest him I thought of using RTK query I think RTK query is quite good when you already using redux isn't it?
Love videos like this. Used to hate query after stumbling on some code that used it because the code had used it weirdly, but seeing this, I love it and am only gonna be using query moving forward
Meanwhile Angular just uses RxJS inside and out with support for templating with observables, SolidJS and Svelte went the "Signals" way, which is kinda neat too
other frameworks like Svelte, Solid or Vue face the same async state management issues too, and they do have adapters to work with Tanstack Query (aka, React Query), because Tanstack Query's implementation is framework-agnostic. The only framework that came built-in with a truly fully-feature HttpClient would be Angular, which is based on Observable and can do async state management out of the box, e.g. set/unset Loading, catch error, debounce, cancellable. The problem is it is too specific to Angular and cannot be easily re-used by other frameworks, like Tanstack Query.
@@vutruong4164 RxJS is not framework specific, Angular's HttpClient is almost just a wrap around fetch converting it to a cancellable observable, I did a quick google here and theres RxJS for React, but I have to say it looks kinda ugly
@@figloalds RxJS is not "framework-specific" in the same way Redux isn't. As in the authors want to believe they wrote a cool general abstraction which can be used everywhere, but it is so boilerplate-ridden and error-prone that you have to use another library to work with the framework of choice. And it becomes the de facto way of using the state management. That's why when you hear "Redux" you instantly associate it with React codebase, even though ACKSHUALLY it's React Redux which associates Redux with React. On top of that Redux has another abstraction called Redux Toolkit which brings a lot of things, a set of rules to deal with async state management and its error handling among the most important ones, which were suspiciously absent from base Redux. I didn't use RxJS but, looking at its basic concept, looks like it can easily become a hell of callbacks with quadrillion layers of indirection, with guidelines on error handling completely absent. I bet it's a lot nicer to use within Angular and you yourself think of angular code snippets when saying "RxJS".
I've used react query in the past, but there is 1 simple reason I dont use it: I want to test how good my own software can hold up and how expandable it is. I know that since its a solo project it will probably never reach levels of react query, but just the fun of building and actually using stuff is already enough to not only boost your ego, performance (maybe) and your experience that its worth it in most cases
please pet the cat
Are you talking or the toxoplasmosis in your brain?
@@bobobo1673did you even watch the video till the end?
@@bobobo1673 what's a toxopalsmosis
i cant believe he didnt pet the cat on cam
@@um_jotas exactly 😔 poor cat
"I am a cat. I am here. I am important." 😻
When you use React Query, achieving caching and optimistic updates becomes very easy, and as a result, your app feels fast. By using a stale time, you can reduce network requests if your data doesn't change frequently... I personally love react query.
if i decide to use reactQuery , do i need another state manager ? , like redux or zustand for the client side, or just using React Query is fine ?
@@freezzefx2670
No, you don't have to use any other state management library along with React Query. React Query handles its own states, and you can access different state values by destructuring them like this:
const { data, isLoading, isError } = useQuery('myQueryKey', fetchDataFunction);
It is like this: Initially, when your component mounts, isLoading becomes true. So, while fetching data, you can show a loading indicator. If something goes wrong, isError will become true, allowing you to show a different UI for errors. Once data comes in, it will be available in data, and you can use that data to show your actual UI. All these are states, so as they change, your component will rerender automatically. I have destructured only three properties (data, isLoading, isError), but there are many other properties that you can use; refer to the docs.
@@freezzefx2670 No, you don't have to use any other state management library along with React Query. React Query handles its own states, and you can access different state values by destructuring them like this: const { data, isLoading, isError } = useQuery('myQueryKey', fetchDataFunction);
It is like this: Initially, when your component mounts, isLoading becomes true. So, while fetching data, you can show a loading indicator. If something goes wrong, isError will become true, allowing you to show a different UI for errors. Once data comes in, it will be available in data, and you can use that data to show your actual UI. All these are states, so as they change, your component will rerender automatically. I have destructured only three properties (data, isLoading, isError), but there are many other properties that you can use. refer to the docs.
@@freezzefx2670 No, you don't have to use any other state management library along with React Query. React Query handles its own states, and you can access different state values by destructuring them like this: "const { data, isLoading, isError } = useQuery('myQueryKey', fetchDataFunction)"
It is like this: Initially, when your component mounts, isLoading becomes true. So, while fetching data, you can show a loading indicator. If something goes wrong, isError will become true, allowing you to show a different UI for errors. Once data comes in, it will be available in data, and you can use that data to show your actual UI. All these are states, so as they change, your component will rerender automatically. I have destructured only three properties (data, isLoading, isError), but there are many other properties that you can use; refer to the docs.
@@freezzefx2670 No, you don't have to use any other state management library along with React Query. React Query handles its own states, and you can access different state values by destructuring them. Unfortunately, I can't provide a code example here because RUclips removes my comment if I do so.
It is like this: Initially, when your component mounts, isLoading becomes true. So, while fetching data, you can show a loading indicator. If something goes wrong, isError will become true, allowing you to show a different UI for errors. Once data comes in, it will be available in data, and you can use that data to show your actual UI. All these are states, so as they change, your component will rerender automatically. I have destructured only three properties (data, isLoading, isError), but there are many other properties that you can use; refer to the docs.
The draw to start using react-query was essentially I could completely isolate components with it’s data fetching, and when another component tries to fetch the same data it’s smart enough to only send one request.
It makes moving around components in different ui’s great, because the data logic is also encapsulated.
I did this via simple events and a hook and packaged it as react-state-events.
indeed moving components around is now really easy and the code redesign was also very very simple in an existing project.
I discovered this channel lately, a true treasure, u got all my love and respect
Totally agree. I am currently working in 2 projects in my company. One with redux as global store and the other with react-query. The main problem I face while using redux would be the caching and loading state. When things get complicated and you have to make 3-4 dispatch calls in a function, then maintaining the loading state with redux becomes very difficult. Also the isLoading and isFetching in react query can be very handy, showing different loaders at different instances in an app.
Another niche case with react query is that when you want to cancel pending queries on unmount of a component, it can be achieved by just passing the abort signal at the right place.
PS: Left out a major thing, in instances when you're firing a post request, you can invalidate the get query and it cleans the cache, which will require additional lines of code at numerous places (depending on your application) while using redux.
@liftwithamey all the api responses are cached in react query based on the query key. So if you set refetch on mount to false, it will use the cached data which is basically useSelector in case of redux.
wouldn't rtk-query have fit since you were already using redux?
@@ssk7690I just took out logic out of UI code and everything became very obvious. Now a regular JS class tells React what to do through events and React updates accordingly. I can get as async and complex as I want and the UI code stays very simple and readable.
Caching? I'll just stash it in the controller. Need a sequence of requests? just regular async/await does it, then publish success or failure accordingly. Cancels? push/pull a list of them in the controller. React doesn't need to know about that.
@@MadsterV by cancelling pending queries I meant something else. Let’s see this with an example. Say you’re firing 10 api calls on a page. Now if the user clicks on a different tab within the page, by default the api calls in second page wouldn’t start until the previous 10 are completed. Hence the need to cancel the pending queries based on user activity. This can be achieved very easily using react query, all you’ll need is the query key.
clear signs of cat mistreatment here.
Not enough immediate unconditional attention
also unsolicited misplacement away from the headscratcher device
lmao
bet you are a cat, an orange one specifically, thats why you are writing this
It's like just HAVING your server state, right there, updated, ready to go at all times. Tanner is amazing. THANK YOU for React Query brother.
Would be of a great value if you share how do you organise code for big projects such as Twitch - folders, components, naming, etc.
I mean, you probably already read it, but LIFT principles from Angular are really useful for this.
As long as you use the react query in component / customhook it's fine. The last issue I have faced is query on click... and yeah someone of you may say "hey there is simple 'refetch' method" but well it's not that easy:
1. query function is a hook so I cannot use it simply like: if args is passed then fetch the query -> you have to wrap it in additional components/ wrapper
2. refetch method is not using the data stored in react-query context e.g. 1. manually query ('refetch') was about "dogs", 2. was about "cats", 3. was about "dogs". Suprise even the data was already in context the api call has been invoked.
for me RTK query is much better ;)
give kitty lovinnnnsss. Thank Theo for this awesome run down on react query. You really helped solidified it's use cases for me : )
react-query still using useEffect under the hood, everything is based on the specific use case. also there are other libraries like RTK that provide similar functionalities.
and ???
it uses a mixture of useEffect and useSyncExternalStore
so what? the only time i don't see react-query necessary is when (no framework obv)
- you need to do pooling quickly for one thing .. and planning later on to use Websocket/SSE
Great point that react-query isn't a fetching library,, but an async state management library (tanner should look into rebranding away from the phrase "query" then). Instead of the common question ppl ask "do I need react-query if I'm already using server components", think you can help explain when we need client side fetching when we already have fetching server side
React query rocks, even for use cases where using ssr and rsc. Major kudos and thanks to team tanstack. There’s also rtk query, which I like/prefer in some ways, but react query nails all the use cases like handling ssr and infinite query. I can’t imagine handling async state using use effect- my gawd.
This just opened my eyes sensei . Arigato
With SWR we got rid of the whole global state management on our project. Awesome stuff.
@@smithrockford-dv1nb you're thinking of SWC (speedy web compiler). SWR is a cache invalidation strategy (stale while revalidate). I believe it's also a useQuery-like library from vercel.
@@smithrockford-dv1nb that's SWC
@@smithrockford-dv1nbSWR means Stale-While-Revalidate. What you’re referring to is SWC.
@@smithrockford-dv1nb You're confusing it with SWC. SWR is a library by Vercel to do the same thing, though more opinionated focused on data fetching than general async, hence its name (Stale While Revalidate).
How did you handle type safety wheb suspense option enabled? It seems tanstackquery provides useSuspensequery but swr not.
I like how this video is just reading a blog post
I was never introduced to react-query, but after watching this I think I'm going to be using it all over the place now.
You also could add an AbortController and pass the signal to fetch as a prop so that when the useEffect cleans up, it can abort the query so that the browser and backend dont need to keep processing the request.
I fall in love with ReactQuery from the first time❤. Its one of the best library
Surprised you don't use query key factories in your code, this is something I learned from Tkdodo's blog and its been amazing because now I don't have to remember query key names if I want to invalidate them in any place.
Query-Key factory is a godsend.
going to check this out
Ha. I've been saying "Tanstack Query is an async state management library" for ages and at the start, I was trying to figure out why I agreed with you because I can't recall watching anything of yours about Tanstack Query. It's because I watched that exact Jason Lengstorf podcast vod when I was learning about tanstack query.
What about the differences between ReactQuery & useSWR ?
wondering as well
It's slightly easier to handle (no need to do QueryClientProvider/useQueryClient) thing, it's 3 times lighter according to bundlephobia
APIs for cases Theo mentions are the same, the code from this video would work with useSWR exactly the same
Because of worse docs, i had problems making useSWR and Tanstack Table to cooperate (i guess Tanstack tried to vendor lock-in to sway me to use Tanstack/React Query) but i overcame it
2:49 yeah that’s a bug but you don’t need a library to fix that bug, use an abort controller and abort inside your returned useEffect clean up function.
Not too long ago I learned this
This is also a large bit of what HTMX does for you that fetch does not do, hx-sync is absolutely amazing from a state management point of view and fits in perfectly and is a very good example of why declarative fetching at the core of the framework is so much better than imperative fetching in javascript
What about primitive obsession? I like react-query but I am wondering if there is a way to use it together with state machine for use cases where you have some form, some loading state, possible error state, confirmation of request send state and so on. I would like to use it in state machine, not always check if I have data or error
absolutely. react-query expects a rather specific use case and once you step out of it, you're on your own.
I moved logic out of React code into a regular JS controller class and just use a simple pub/sub to communicate events from the controller to the UI through a subscription hook (react-state-events). Then everything clicked without the need for awkward hooks and rendering weirdness (I did use a very simple state machine!). Controller offers methods which are hooked to UI controls and UI updates as needed when the controller decides to do so.
I can even call the controllers from other components if I wish to do so. I can unmount and keep the controller alive to remount UI later, in a different place or even mount many different components at the same time that render the same data in different ways. Very flexible with minimal boilerplate!
No useEffect, no double calls, no undesired renders. Just a plain class sending UI events and a plain React component rendering whatever the events say.
Nice video Theo. This is what pisses me off sooooo much about React coming from Svelte, these one-off packages that are required to do basic stuff the framework should be providing a solution for (IMHO)
I used to feel this way more, but then I had to do long-term maintenance on some Angular apps? I started to much prefer a more modular approach. I think the reality is that the "official" version would work half as well and would reduce the support given to alternatives. At the very least, there's tradeoffs.
@@Nassifeh This is actually a pretty good point I can see where you’re coming from. I’ll probably feel less salty once I get better at using these 3rd party react packages
@@MerkieAE It's definitely an adjustment period, even if I'm in favor of it. 😩 I miss when every guide or tutorial was doing stuff the same way I am. But I won't miss having to update basically the whole app all at once twice a year.
But React isn't a Framework. It's a JavaScript library. It wasn't meant to handle data fetching built-in.
Theo, appreciate your frequent videos!
can't wait to hear from you about the fetch not throwing situation
I was not able to hide my teeth throughout the video - very nicely explained
I love react-query and go with all of our arguments. I see problems with useEffect elsewhere though. It's used when reducers should be employed. I build complex CMS where you have loads of changees to the client state of the object fetched and eventually saved to the server. Saw people jerking useState and useEffect to manage that. All removed by simple useReducer or redux with some thunks from time to time. I think as state manager, when you do many updates to the client state (like in my case) keeping things out of the react-query and in reducers is simpler, especially if you don't want to run into key management hell. Compared to your example for non-fetch examples, it may be why reducers work better in that case is that structure of my model is unpredictable and can be deeply nested.
Yeah. If you use optimistic updates so much that your data is basically just state, with an extra database synchronization step, you should embrace a state manager for it, not a query manager.
can i still use React useQuery on my nextjs application or just use built in data fetching on server components ?
React Query Doesn't work really well with server components. Nextjs fetching api comes with caching, revalidation already so react query is not really necessary
I'm happy, Brain Holt said the very same things 1,5 years ago at frontend masters. :)
thoughts on RTK Query?
The article states that the custom fetch hook is spaghetti code, like what do you think is going on in React Query behind the scenes? black magic?
Before React Query came along every senior dev would create their own query custom hook, and that's the thing the team at Tanstack did, they just turned into a library and added a ton more of functionality.
If you just need to make simple requests, making a good custom fetch hook is a good solution, React Query didn't invent data fetching and it shouldn't be imposed as the only solution.
Critically, React Query is not using useEffect under the hood (for the fetching bit).
@@stoogel what's using? There's no alternative to useEffect for connecting to external APIs in React as far as I know.
.
I didn't even know you have a cat on your crew! Loving it! What's the name?
Were you the one on picturepunches back in 2018, 2019 ??
I'm new to react. Why do we need to do useEffect just to populate a form? For example...
```
const MyFormComponent = ({ selectOptions }) => {
const [options, setOptions] = useState(selectOptions);
return (
Options:
{options.map((option) => (
{option.label}
))}
);
};
```
It was a great video!😊
hey man, I watched your videos a lot but I never subscribe. 🤣 but when you show your cat at the end of the video 🤩 aww so cute I need to click subscribe now.
my guesses for the 5 potential bugs:
- out of order responses when category changes
- data and error set simultaneously, not properly overriding both values when category changes
- stale result being used when category changes
- not properly accounting for bad status code (that depends on the api really)
- cannot determine loading state because of default data empty array value
- fetching not cancelled when component unloaded
This is very awesome indeed.
I also use it but I still do not know why they don't have an own fetch function, you still have to change the default behavior of fetch to make it fully correcttly working with react query
This is great. Thanks!
If the core methods are so perilous, it seems like the argument could be made that this should be in the core framework.
The API should be improved so that the right way is the easy and obvious way, yes?
How to use query outside a component? When it’ll be possible maybe it’ll be a good time to use it.
I love the data selectors feature in React Query
Amazing content! Thank you so much!!!
Is ignore variable shareable between useEffect calls
It should be but why?
Fascinating you changed my mind
Good to see our cats behave the same way around laptops
Thanks for your quick talking it helps us who haven't been fluent in English yet. Anyway please try to talk in a normal speed.
Great vid. Opinion vs SWR?
I am at end of video but I am still not able to figure it out if he has blonde hair or colored his mustache. :)
I'm doing something at work at the moment with Launch Darkly (feature flagging tool). Whenever the user changes, we tell launch darkly, and that gives us updated feature flags based on the data sent. In order to access the flags we have to use their client to fetch them. These flags need to fetched asynchronously however they are already cached in the launch darkly client. I ended up just fetching the flags and dispatching to redux whenever we change the user so the UI is always in sync but I'm still debating in my mind whether I should have used React Query... This is React Native btw.
Do you have any thoughts on this?
50-50 here. We used it for a medium project and in some cases we didn't like some of the workarounds and React Query way of doing things. It is a library from another author on how they believe data fetching should be handled, and I respect their opinions, but it is not one stop solution for everything. Not a bad experience, but not an amazing as well. Nevertheless, I have to give credit for an amazing library as a feat in developing it.
I agree with you there, it's a great tool to master, but it's not THE solution to every problem.
Just blabla. Give some actual examples for us to learn from.
@@filipjnc IKR dude just wrote 5 sentences of nothing. "Some cases", yeah lol
I've done CRUD cache engine from the url structure and also doing optimistic CRUD changes (as part of the cache engine) after successful mutations.... Helps me to minimize the codebase, instead of thousand custom hooks files....
8:41 where does signal come from?
My chest started to tighten right at the end of bug #4. I only used react recently and and I made the jump to react query when the mvp got to paid stage, and I am proud to say that I am never going back. 🎉
Signal is the key. Doesn't matter if u use react query or not
I am convinced, i need react query
I use React Server Components for server stuff and tRPC (uses React Query under the hood) for client stuff. Pretty neat
What do you think of rtk query?
Pet the little Tabby thing and then we will all aww ❤❤❤❤
i agree
i will use fetch in my useEffect tho
loh
In my every-day job my team uses redux-saga to achieve pretty much the same thing react-query does: async state management. That said, what are the differences between these two libraries? Is one better than the other? Or everything resolves in “it’s your preference”?
Great video btw!
You probally use sagas "wrong" way. React-Query is 90% same things compared to Redux Toolkit Query - which is solve the 'fetch data' use-case of sagas.
If your daily sagas purpose is :fetch data, update loading, set success, set error, invalidate incomming fetching action, wait another action's data , your work is just overlapping RTKQ - as I said "wrong".
I personally though sagas make no sense to my project since RtkQ released.
Back from start, sagas CAN handles all React-Query usages - but in a dirty way
@@lamhung4899 Thanks for the answer! How would you suggest to use saga in a proper way?
so whenever we need to fetch some data from API or to get async data, then we use react query instead of useEffect(), Then when is good idea to use useEffect()? do we still need it?
Firing off tracking events, subscribing to server sent events or socket events , for example
How would you put React Query against SWR? I have used neither - I'm looking for the best solution.
SWR is a decent way to cache fetch calls. React Query is a groundbreaking way to manage async functions and state in React.
IMO, they’re about as comparable as a toy car and a semi truck
@@t3dotgg Got it, thanks.
I thought react query would handle any errors in the fetch function. should I go back to using try-catch blocks in this kind of function?
React Query is data agnostic, meaning it doesn't care how you provide it the data, via fetch, via XMLHTTTRequest, via axios or pull it from localStorage. All it cares about is that you give it a function that returns some data or throws an error. If the function returns the data it is considers a success, if it throws it is considered an error.
Your cat definitely made the point more valid.
Can you make a video on when you might use react query in a next.js application?
Does it make sanse using React Query in NextJS?
Impressive resistance against the urge to pet the 🐈
Yeah a detailed video on fetching data specially in next js would be great
more cat please, thank you.
If someone is already using redux toolkit for managing states what would you suggest him I thought of using RTK query I think RTK query is quite good when you already using redux isn't it?
red is red, blue is blue
@@raijinhasarrived what if someone is color-blind
Why do not they make react query as a part of native feature of React
Thanks again man!
I feel TanStack utilities to be a bit cumbersome for my taste, they are great but for data fetching I prefer SWR!
We could have just read the blog post?
All he does is spoon-feed the good developers products.
Great! 👍👍👍👍👍👍
I agree about using react query But in the article fetch was used in the most horrible way 😂
talk about useSWR for data fetching aswell and compare the two if you can
Love videos like this. Used to hate query after stumbling on some code that used it because the code had used it weirdly, but seeing this, I love it and am only gonna be using query moving forward
Love react query !!
That cat looks like mine!!!
I ❤ React Query
Meanwhile Angular just uses RxJS inside and out with support for templating with observables, SolidJS and Svelte went the "Signals" way, which is kinda neat too
Was wondering how complex these simple things get in other frameworks
Angular can use signals too now ig
other frameworks like Svelte, Solid or Vue face the same async state management issues too, and they do have adapters to work with Tanstack Query (aka, React Query), because Tanstack Query's implementation is framework-agnostic.
The only framework that came built-in with a truly fully-feature HttpClient would be Angular, which is based on Observable and can do async state management out of the box, e.g. set/unset Loading, catch error, debounce, cancellable. The problem is it is too specific to Angular and cannot be easily re-used by other frameworks, like Tanstack Query.
@@vutruong4164 RxJS is not framework specific, Angular's HttpClient is almost just a wrap around fetch converting it to a cancellable observable, I did a quick google here and theres RxJS for React, but I have to say it looks kinda ugly
@@figloalds RxJS is not "framework-specific" in the same way Redux isn't. As in the authors want to believe they wrote a cool general abstraction which can be used everywhere, but it is so boilerplate-ridden and error-prone that you have to use another library to work with the framework of choice. And it becomes the de facto way of using the state management. That's why when you hear "Redux" you instantly associate it with React codebase, even though ACKSHUALLY it's React Redux which associates Redux with React. On top of that Redux has another abstraction called Redux Toolkit which brings a lot of things, a set of rules to deal with async state management and its error handling among the most important ones, which were suspiciously absent from base Redux.
I didn't use RxJS but, looking at its basic concept, looks like it can easily become a hell of callbacks with quadrillion layers of indirection, with guidelines on error handling completely absent. I bet it's a lot nicer to use within Angular and you yourself think of angular code snippets when saying "RxJS".
Most of my project use Redux (unfortunately), so it's easily for me to use RTK Query instead of React Query.
💯
Yeah use react guys, keep adding those small dependencies again again and again
RTK Query?
This video hit JIT; Past 2 days I have been searching for a source which can justify the use of react-query. Thanks Theo!
WE NEED MORE CAT IN THE VIDEOS
yeah but isn't called Tanstack Query? It's supposed to support more than React
This is definitely something that separates the more junior from the more senior devs. I love using react query for all these reasons
I've used react query in the past, but there is 1 simple reason I dont use it: I want to test how good my own software can hold up and how expandable it is. I know that since its a solo project it will probably never reach levels of react query, but just the fun of building and actually using stuff is already enough to not only boost your ego, performance (maybe) and your experience that its worth it in most cases
That's extra time that most of us don't have or want to spend.
@@CapzTube yea if you are on the job that's probably not what you want to do, but for personal projects I like to go to a from scratch approach
For the job it's company time. Nothing wrong with wasting that
@@joshix833 until your manager asks why you've been wasting time on something the company doesn't need.
@@joshix833 depends on how much you like the company tbh
redux rtk is way if you already have complex state system
When i was a child ,my mom closed my shirt top button like you did . Is it a new fashion there ? which country do you belong ? 🙃
It would convince me better if when i go to docs, i would see good docs not course selling to learn react query