JAVASCRIPT
Implement Data Fetching with useEffect and Cleanup
Learn to fetch data from an API using React's useEffect hook, including how to properly clean up side effects to prevent memory leaks and ensure optimal component behavior.
import React, { useState, useEffect } from 'react';
function DataFetcher() {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const result = await response.json();
setData(result);
} catch (err) {
setError(err);
} finally {
setLoading(false);
}
};
fetchData();
// Cleanup function: This runs when the component unmounts or before re-running the effect
// (if dependencies change). For a simple fetch, it might not always be strictly necessary
// to cancel the fetch itself unless using AbortController, but it's crucial for
// things like event listeners, timers, or subscriptions.
return () => {
// For example, if you had a WebSocket subscription:
// unsubscribeFromWebSocket();
// Or if you set a timer:
// clearTimeout(myTimer);
console.log('Component unmounted or effect re-ran. Cleaning up...');
};
}, []); // Empty dependency array means this effect runs once on mount and cleans up on unmount
if (loading) return <div>Loading data...</div>;
if (error) return <div>Error: {error.message}</div>;
return (
<div>
<h1>Data Fetched:</h1>
<p>Title: {data.title}</p>
<p>Body: {data.body}</p>
</div>
);
}
export default DataFetcher;
How it works: This snippet demonstrates how to use the `useEffect` hook to fetch data from an API when a component mounts. The `useState` hook manages the fetched data, loading state, and any errors. The `useEffect` hook is called with an async function to perform the data fetching. Crucially, it returns a cleanup function that executes when the component unmounts or before the effect runs again. While this specific fetch example doesn't show an explicit cancellation (which often involves `AbortController`), the cleanup pattern is vital for removing event listeners, clearing timers, or unsubscribing from services to prevent memory leaks and unwanted side effects.