React Query is a powerful library for managing server state in React applications, providing features such as data fetching, caching, synchronization, and updates. To refetch data from a peer component, leverage the useQueryClient hook provided by React Query. Below are detailed steps and example code:
Steps
-
Ensure React Query is properly set up in your project. Verify your application is wrapped with
QueryClientProviderand passes aQueryClientinstance. -
Use the
useQueryhook in the source component. Here, the "source component" refers to the component responsible for data fetching. -
Use the
useQueryClienthook in the target component to access thequeryClientinstance. This hook grants access to thequeryClientinstance, enabling interaction with the React Query cache and utilities. -
Call the
queryClient.invalidateQueriesmethod in the target component. This method invalidates one or more queries, triggering a refetch. Specify a particular query key to invalidate only those queries.
Example Code
Assume we have two components, ComponentA and ComponentB. ComponentA fetches user data, while ComponentB triggers a refetch of this data.
jsx// App.js import React from 'react'; import { QueryClient, QueryClientProvider } from 'react-query'; import ComponentA from './ComponentA'; import ComponentB from './ComponentB'; const queryClient = new QueryClient(); function App() { return ( <QueryClientProvider client={queryClient}> <ComponentA /> <ComponentB /> </QueryClientProvider> ); } export default App;
jsx// ComponentA.js import React from 'react'; import { useQuery } from 'react-query'; async function fetchUserData() { const response = await fetch('https://api.example.com/users'); if (!response.ok) { throw new Error('Network response was not ok'); } return response.json(); } function ComponentA() { const { data, error, isLoading } = useQuery('users', fetchUserData); if (isLoading) return <div>Loading...</div>; if (error) return <div>Error: {error.message}</div>; return ( <div> {data.map(user => ( <p key={user.id}>{user.name}</p> ))} </div> ); } export default ComponentA;
jsx// ComponentB.js import React from 'react'; import { useQueryClient } from 'react-query'; function ComponentB() { const queryClient = useQueryClient(); const refetchUsers = () => { queryClient.invalidateQueries('users'); }; return ( <button onClick={refetchUsers}>Refetch Users</button> ); } export default ComponentB;
Summary
In this example, ComponentA uses useQuery to fetch user data. ComponentB includes a button that, when clicked, triggers a refetch by calling queryClient.invalidateQueries('users'). This approach promotes component decoupling, as they interact through query keys (e.g., 'users') rather than direct references or state lifting. This enhances maintainability and scalability of the code.