Hello fellow developer in this article we are going to learn how to add react-query library to your react application and how to setup react query in you application.
Use following command to add react-query in your application:
npm i @tanstack/react-query or yarn add @tanstack/react-query
For using react query in our application we need to wrap our files with QueryClientProvider you can wrap you app.js file with this like the example given below:
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> ) }
Then pass query client as a prop in you wrapper, This is it for the setup of your react-query, now a user can use react query any where in its application.
Just import usequery in your component as shown above in the application.
React query has 3 core concepts which we we are going to learn about in upcoming blogs:
- Queries
- Mutations
- Query Invalidation
That’s it for this blog please feel free to comment regarding any queries.