Fetching data with traditional methods like fetch() or axios.get() often requires making changes to your App.js to ensure the API is hit only once. This can be cumbersome, especially when dealing with React's Strict Mode, which enforces best practices by intentionally double-invoking certain lifecycle methods in development. Removing Strict Mode to avoid these issues is generally considered a bad practice.
React Query simplifies data fetching and mutation processes by abstracting much of the repetitive code involved in requesting and sending data to an API. It provides an efficient and declarative way to manage server state in your application, handling caching, background updates, and synchronization with the server.
To use the React Query library, install it using the following command:
npm install @tanstack/react-query
import React from 'react';
import { useQuery, QueryClient, QueryClientProvider } from '@tanstack/react-query';
import axios from 'axios';
// Create a client
const queryClient = new QueryClient();
const fetchUsers = async () => {
const { data } = await axios.get('<https://jsonplaceholder.typicode.com/users>');
return data;
};
const UsersList = () => {
const { data, error, isLoading, isError } = useQuery(['users'], fetchUsers);
if (isLoading) {
return <div>Loading...</div>;
}
if (isError) {
return <div>Error: {error.message}</div>;
}
return (
<ul>
{data.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
};
const App = () => (
<QueryClientProvider client={queryClient}>
<div>
<h1>Users</h1>
<UsersList />
</div>
</QueryClientProvider>
);
export default App;