Handle asynchronous data, API calls, caching, and complex interactions with grace.
Working with APIs is a fundamental skill in modern web development. APIs allow your React applications to interact with external data sources, enabling you to create dynamic and interactive user experiences.
The fetch API is a built-in JavaScript method for making HTTP requests. It's a modern alternative to the older XMLHttpRequest object.
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
While fetch is built into JavaScript, axios provides additional features like error handling and request cancellation.
axios.get('https://api.example.com/data')
.then(response => console.log(response.data))
.catch(error => console.error('Error:', error));
Good user experiences require proper handling of loading and error states. Use state management to track the status of API requests.
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const [data, setData] = useState([]);
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
setLoading(false);
setData(data);
})
.catch(error => {
setLoading(false);
setError(error);
});
REST (Representational State Transfer) is a popular architectural style for designing networked applications. It uses standard HTTP methods to perform operations on resources.
GraphQL is an alternative to REST that allows clients to request exactly the data they need. It's particularly useful for complex applications with many interrelated resources.
const query = `
{
user(id: 1) {
name
email
posts {
title
content
}
}
}`;
Reusable data-fetching logic can save time and reduce code duplication. Consider creating custom hooks or utility functions.
const useData = (url) => {
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const [data, setData] = useState([]);
useEffect(() => {
const controller = new AbortController();
axios.get(url, { signal: controller.signal })
.then(response => {
setLoading(false);
setData(response.data);
})
.catch(error => {
setLoading(false);
setError(error);
});
return () => controller.abort();
}, [url]);
return { loading, error, data };
};
Welcome to the chapter on Data Fetching Libraries! Modern web development often requires fetching and managing data asynchronously. While React provides built-in hooks like useEffect
, handling data fetching efficiently can be challenging. That's where libraries like React Query and SWR come into play, offering powerful solutions for managing asynchronous state, caching, and synchronization.
React Query is a popular library for managing server state in React applications. It provides a simple yet powerful API for fetching, caching, and synchronizing data. Key features include:
// Install dependencies
npm install react-query @tanstack/react-query-devtools
// Example usage
import { useQuery } from '@tanstack/react-query';
function UsersList() {
const { data, error, isLoading } = useQuery({
queryKey: ['users'],
queryFn: async () => {
const response = await fetch('https://api.example.com/users');
return response.json();
},
});
if (isLoading) return <div>Loading...</div>;
if (error) return <div>Error!</div>;
return (
<ul>
{data.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
SWR (Server-Waiting-Response) is another lightweight and flexible library for data fetching in React. It focuses on providing a simple API while offering powerful features like revalidation, pagination, and deduping.
// Install dependencies
npm install swr
// Example usage
import useSWR from 'swr';
function UsersList() {
const { data, error } = useSWR('https://api.example.com/users');
if (error) return <div>Error!</div>;
if (!data) return <div>Loading...</div>;
return (
<ul>
{data.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
Both libraries are excellent choices for data fetching in React, but they differ in their approach and features:
To maximize the benefits of data fetching libraries, follow these best practices:
Both React Query and SWR are widely used in production applications. They're especially useful in scenarios like:
Question 1 of 10