Back to articles
React Query (TanStack Query) Has a Free API — Here's How to Manage Server State

React Query (TanStack Query) Has a Free API — Here's How to Manage Server State

via Dev.to ReactAlex Spinov

TanStack Query (formerly React Query) is the gold standard for server state management. It handles caching, background refetching, pagination, optimistic updates, and more. Installation npm install @tanstack/react-query Setup import { QueryClient , QueryClientProvider } from " @tanstack/react-query " ; const queryClient = new QueryClient ({ defaultOptions : { queries : { staleTime : 5 * 60 * 1000 , retry : 3 } } }); function App () { return ( < QueryClientProvider client = { queryClient } > < MyApp /> </ QueryClientProvider > ); } useQuery — Fetch Data import { useQuery } from " @tanstack/react-query " ; function Posts () { const { data , isLoading , error } = useQuery ({ queryKey : [ " posts " ], queryFn : async () => { const res = await fetch ( " /api/posts " ); if ( ! res . ok ) throw new Error ( " Failed to fetch " ); return res . json (); } }); if ( isLoading ) return < p > Loading... </ p >; if ( error ) return < p > Error: { error . message } </ p >; return ( < ul > { data . map

Continue reading on Dev.to React

Opens in a new tab

Read Full Article
2 views

Related Articles