JAVASCRIPT
Simple Data Fetching in React with a useFetch Custom Hook
Implement a straightforward useFetch custom hook in React using useEffect and useState for basic asynchronous data retrieval and state management.
import { useState, useEffect } from 'react';
function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const abortController = new AbortController();
const signal = abortController.signal;
const fetchData = async () => {
setLoading(true);
setError(null);
try {
const response = await fetch(url, { signal });
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const result = await response.json();
setData(result);
} catch (err) {
if (err.name === 'AbortError') {
console.log('Fetch aborted');
return;
}
setError(err);
} finally {
setLoading(false);
}
};
fetchData();
return () => {
abortController.abort(); // Cleanup on unmount or URL change
};
}, [url]);
return { data, loading, error };
}
// Example Usage:
// function PostViewer({ postId }) {
// const { data: post, loading, error } = useFetch(
// `https://jsonplaceholder.typicode.com/posts/${postId}`
// );
// if (loading) return <p>Loading post...</p>;
// if (error) return <p>Error: {error.message}</p>;
// if (!post) return null;
// return (
// <div>
// <h2>{post.title}</h2>
// <p>{post.body}</p>
// </div>
// );
// }
How it works: This `useFetch` hook simplifies fetching data from an API endpoint in React components. It uses `useState` to manage the data, loading state, and any errors. The `useEffect` hook handles the asynchronous `fetch` call when the `url` changes. It includes basic error handling and utilizes `AbortController` for cleanup, preventing memory leaks or state updates on unmounted components if the component unmounts before the fetch completes. It returns an object containing the fetched `data`, `loading` status, and `error` object.