React-Query is a powerful library for managing and caching data fetching in React applications. It simplifies the process of fetching, caching, and updating data in your components. Here's a step-by-step guide on how to use React-Query for data fetching:
You can install React-Query using npm or yarn:
bash# Using npm
npm install react-query
# Using yarn
yarn add react-query
Wrap your application with the QueryClientProvider
to make the React Query functionality available to your components.
jsx// In your main app file (e.g., App.js)
import React from 'react';
import { QueryClient, QueryClientProvider } from 'react-query';
const queryClient = new QueryClient();
function App() {
return (
<QueryClientProvider client={queryClient}>
{/* Your app components go here */}
</QueryClientProvider>
);
}
export default App;
useQuery
Now you can use the useQuery
hook in your components to fetch data. Here's a simple example:
jsx// In your component file
import React from 'react';
import { useQuery } from 'react-query';
const fetchData = async () => {
// Your data fetching logic (e.g., fetch from an API)
const response = await fetch('https://api.example.com/data');
const data = await response.json();
return data;
};
function MyComponent() {
const { data, error, isLoading } = useQuery('myData', fetchData);
if (isLoading) {
return <p>Loading...</p>;
}
if (error) {
return <p>Error: {error.message}</p>;
}
// Render your component with the fetched data
return (
<div>
<h1>Data:</h1>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
);
}
export default MyComponent;
In this example:
useQuery
takes a query key ('myData'
) and a function (fetchData
) that returns a promise.React Query provides a way to manually trigger a refetch of your data. For example, you can use the refetch
function returned by useQuery
:
jsxfunction MyComponent() {
const { data, error, isLoading, refetch } = useQuery('myData', fetchData);
const handleButtonClick = () => {
// Manually trigger a refetch
refetch();
};
// ... rest of the component
}
useMutation
If you need to update data on the server, you can use the useMutation
hook:
jsximport { useMutation } from 'react-query';
const updateData = async (newData) => {
// Your mutation logic (e.g., updating data on the server)
const response = await fetch('https://api.example.com/update', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(newData),
});
const updatedData = await response.json();
return updatedData;
};
function MyComponent() {
const mutation = useMutation(updateData);
const handleUpdate = async () => {
try {
// Call the mutation function with the new data
const updatedData = await mutation.mutateAsync({ newData: 'your new data' });
// Handle the updated data
console.log('Updated Data:', updatedData);
} catch (error) {
// Handle the error
console.error('Mutation Error:', error);
}
};
// ... rest of the component
}
This example shows how to handle mutations and update data on the server using useMutation
.
These are the basic steps to get started with React-Query for data fetching in a React application. The library provides many more features and options for customization, so be sure to check the official documentation for more advanced use cases.