Hello Fellow Developers, In this blog we are going to talk about why should we use react-query and what difference it makes from normal data fetching in react. What are the other libraries we can use if we are not using react – query.
React Query is described as missing data-fetching library for React, but more in technical terms, it make fetching, caching, synchronizing and updating server state in your React application breeze. React do not come with a standard way of fetching data so developer creates there own ways of fetching and maintaining data in there components.
Well, using this libraries in react are great with client side but not so great when it comes to server state, Challenges we face while maintaining server state:
- It is persisted remotely in location you do not control or own
- It requires asynchronous APIs for fetching and updating
- It Implies shared ownership and it can be changed by other people without your knowledge
- Data can potentially become out of date in your applications if you’re not careful
- Caching
- Multiple requests for the same data into a single request
- Updating out of date data in background
- Reflecting update to data as quickly as possible
- Performance optimization like pagination and lazy loading data
- Managing memory and garbage collection of server data
- Memorizing query result with structural sharing
These are all the problems a developer faces while fetching data from server state and react query solves all the problems let me show you guys a small code where react query handles loading and manages errors.
import { QueryClient, QueryClientProvider, useQuery } from '@tanstack/react-query' const queryClient = new QueryClient() export default function App() { return ( <QueryClientProvider client={queryClient}> <Example /> </QueryClientProvider> ) } function Example() { const { isLoading, error, data } = useQuery(['repoData'], () => fetch('https://api.github.com/repos/tannerlinsley/react-query').then(res => res.json() ) ) if (isLoading) return 'Loading...' if (error) return 'An error has occurred: ' + error.message return ( <div> <h1>{data.name}</h1> <p>{data.description}</p> <strong>👀 {data.subscribers_count}</strong>{' '} <strong>✨ {data.stargazers_count}</strong>{' '} <strong>🍴 {data.forks_count}</strong> </div> ) }
See a neat and clean code. Other library that we can use instead or react query as a option which solves same problem is applo client. There will be more options like these but if you like react query then stick with me in the series of next articles where we explore and learn how to use react query in an application.