Posts > React Query Basic
July 8, 2024
I’ve been using React Query for some time now but didn’t really understand it as I’ve used my old company project code in React Query and used it on my other projects without knowing why the code does that. This time I tried learning it through the documentation and courses. ( Yes I bought a course so sue me! )
In a way, I somehow got it now. So writing this so that in the future ( because I’m old and forget things a lot ) I will refer to this. And this will be a series like the React Typescript that is not yet finished 😅
👌Combining useState, useEffect, and Context together in an attempt to “manage” state will lead to pain and suffering.
Manage server state without doing a lot of work 😉.
And of course, React Query can handle this for you
React-query is an async state manager that is also acutely aware of the needs of the server state.
React Query doesn't fetch data for you, instead, you provide it with a promise and it will then take the data that the promise resolves with and make it available wherever you need it on your application.
Installation
npm i @tanstack/react-query
pnpm add @tanstack/react-query
yarn add @tanstack/react-query
bun add @tanstack/react-query
Using it!
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
const queryClient = new QueryClient();
export default function App(){
return (
<QueryClientProvider clinet={queryClient}>
<App />
</QueryClientProvider>
)
}
QueryClinetProvider
component and passing the queryClient
as a client
prop, React Query will make the query cache available to you anywhere in your component tree.useQuery
const { data } = useQuery({
queryKey: ['movie'],
queryFn: () => Promise.resove()
})
queryKey
queryKey
, useQuery
will return that data immediately making it so you don’t have to fetch your API again. Otherwise, it will invoke the queryFn
which you provided a promise-based method and then put in the cache of the queryKey
queryFn