Posts > React Query Basic

React Query Basic

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 😅

Why use React-query?

👌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

  1. Cache management
  2. Cache invalidation
  3. Auto refetching
  4. Window focus fetching
  5. Dependent queries
  6. Paginated queries
  7. Request cancellation
  8. Prefetching
  9. Polling
  10. Mutation
  11. Infinite scrolling
  12. and many more!

React Query is NOT a data fetching library

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.

Fundamentals

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>
	)
}
  • wrapping your MAIN parent component inside the 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.
  • with this it allows you to access the cache and interact with React Query wherever you want, without having to worry about triggering unnecessary re-renders.

useQuery

const { data } = useQuery({
	queryKey: ['movie'],
	queryFn: () => Promise.resove()
})

queryKey

  • should be globally unique
  • by default if there’s already data allocated in the cache of the 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

  • must return a promise that resolves with the data you want to cache.