What is React Query
The react query is a library for fetching data in React application. So, in this article is about what is react query used for.
Why would you need a library for data fetching
Since React is a UI library, there is no specific pattern for data fetching. What we typically do is make use of effect hook for data fetching and use state hook to maintain component state like loading or the resulting data. But what is important to note here is that most of the state management libraries are good at working with the client state.
They are not great for working with asynchronous or server states because the server state is very different from the client state.
Client vs Server state
It is persisted in your app memory and accessing or updating it is synchronous.
- Server state on the other hand is persisted remotely in a database perhaps and requires asynchronous APIs for fetching or updating.
- Also, the server state unlike the client state has shared ownership
- Data can be updated by someone else without your knowledge which can quickly lead to UI data that is not in sync with the remote data.
- It becomes even more challenging when you have to deal with caching, deduping multiple requests for the same data, updating stale data in the background, performance optimization when it comes to pagination and lazy loading, etc.
If you have to cater to all these in an application, it requires significant time and effort to do it all by yourself. You can take the smarter approach and use a library which makes handling all these scenarios a walk in the park. You have probably guessed that the library is reacted query. Before learning React query you must know the basics fundamentals of React and React hooks.