error-handling fetch-api web-development javascript frontend-development react usestate custom-hook api-requests data-fetching
React Custom Hook for API Requests
This snippet provides a custom hook to manage the lifecycle of API requests in a React application, offering a clean and reusable way to handle data fetching.
Custom Hook: useFetch
import { useState, useEffect } from 'react';
function useFetch(url, options = {}) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
let isMounted = true; // Track if component is mounted
const fetchData = async () => {
setLoading(true);
try {
const response = await fetch(url, options);
if (!response.ok) {
throw new Error('Network response was not ok');
}
const result = await response.json();
if (isMounted) {
setData(result);
}
} catch (error) {
if (isMounted) {
setError(error);
}
} finally {
if (isMounted) {
setLoading(false);
}
}
};
fetchData();
return () => {
isMounted = false; // Cleanup to avoid setting state on unmounted component
};
}, [url, options]);
return { data, loading, error };
}
export default useFetch;
Using the Custom Hook
Here’s an example of how to use the useFetch
hook in a React component to fetch and display data.
import React from 'react';
import useFetch from './useFetch'; // Ensure correct import path
function UserList() {
const { data, loading, error } = useFetch('https://jsonplaceholder.typicode.com/users');
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;
return (
<ul>
{data.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
export default UserList;
Features and Benefits
- Reusability: The
useFetch
hook can be used across different components and applications, reducing code duplication and simplifying API interaction.
- Loading and Error States: Automatically manages loading and error states, providing a consistent way to handle asynchronous operations.
- Cleanup Handling: Prevents state updates on unmounted components, reducing potential memory leaks and ensuring stability.
Customization and Extension
- Custom Headers: Extend the hook to accept custom headers or authentication tokens in the
options
parameter.
- Polling: Implement a polling mechanism by setting up a
setInterval
within theuseEffect
for periodically fetching data.
- Data Transformation: Add a callback function to transform the fetched data before setting it in state.
Comments
Please log in to leave a comment.