5+ years web developer
5+ years web developer
5+ years web developer
5+ years web developer
React Query is a powerful tool that simplifies data fetching in React applications. It provides hooks to manage server-state, caching, and synchronization, making it easier to handle asynchronous operations.
To start using React Query, install it via npm:
bash1npm install @tanstack/react-query
Then, wrap your application with the QueryClientProvider
:
jsx1import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; 2 3const queryClient = new QueryClient(); 4 5function App() { 6 return ( 7 <QueryClientProvider client={queryClient}> 8 {/* Your application components */} 9 </QueryClientProvider> 10 ); 11}
Now, you can use the useQuery
hook to fetch data:
jsx1import { useQuery } from '@tanstack/react-query'; 2 3function Posts() { 4 const { data, error, isLoading } = useQuery({ 5 queryKey: ['posts'], 6 queryFn: fetchPosts 7 }); 8 9 if (isLoading) return <div>Loading...</div>; 10 if (error) return <div>Error loading posts</div>; 11 12 return ( 13 <ul> 14 {data.map(post => ( 15 <li key={post.id}>{post.title}</li> 16 ))} 17 </ul> 18 ); 19}
For creating, updating, or deleting data:
jsx1import { useMutation, useQueryClient } from '@tanstack/react-query'; 2 3function CreatePost() { 4 const queryClient = useQueryClient(); 5 6 const mutation = useMutation({ 7 mutationFn: createPost, 8 onSuccess: () => { 9 queryClient.invalidateQueries({ queryKey: ['posts'] }); 10 }, 11 }); 12 13 return ( 14 <button onClick={() => mutation.mutate({ title: 'New Post' })}> 15 Create Post 16 </button> 17 ); 18}
For paginated data:
jsx1import { useInfiniteQuery } from '@tanstack/react-query'; 2 3function InfinitePosts() { 4 const { 5 data, 6 fetchNextPage, 7 hasNextPage, 8 isFetchingNextPage, 9 } = useInfiniteQuery({ 10 queryKey: ['posts'], 11 queryFn: ({ pageParam = 0 }) => fetchPosts(pageParam), 12 getNextPageParam: (lastPage, pages) => lastPage.nextCursor, 13 }); 14 15 return ( 16 <div> 17 {data?.pages.map((page, i) => ( 18 <div key={i}> 19 {page.posts.map(post => ( 20 <div key={post.id}>{post.title}</div> 21 ))} 22 </div> 23 ))} 24 <button 25 onClick={() => fetchNextPage()} 26 disabled={!hasNextPage || isFetchingNextPage} 27 > 28 {isFetchingNextPage ? 'Loading...' : 'Load More'} 29 </button> 30 </div> 31 ); 32}
React Query has become an essential tool in the React ecosystem, and for good reason. It solves many common problems developers face when working with server state, making applications more performant and user-friendly.
For more details, refer to the official React Query documentation.