Day 32: The UseEffect Hook
The useEffect hook in React is a fundamental feature that allows you to perform side effects in function components. Side effects include operations like data fetching, subscriptions, or manually changing the DOM. Prior to hooks, such operations were handled in class component lifecycle methods such as componentDidMount, componentDidUpdate, and componentWillUnmount. The useEffect hook consolidates these functionalities into a single API, simplifying component logic.
Basic Usage:
javascript
CopyEdit
import { useEffect } from 'react';
function MyComponent() {
useEffect(() => {
// Code to run on component mount
return () => {
// Cleanup code to run on component unmount
};
}, [dependencies]);
}
- The first argument is a function containing the side effect code.
- The optional second argument is an array of dependencies.
- If provided, the effect runs after the initial render and whenever any dependency changes.
- If omitted, the effect runs after every render.
- If an empty array is provided, the effect runs only once after the initial render.
Example: Fetching Data
javascript
CopyEdit
import { useState, useEffect } from 'react';
function DataFetcher() {
const [data, setData] = useState(null);
useEffect(() => {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => setData(data))
.catch(error => console.error('Error fetching data:', error));
}, []); // Empty array means this effect runs once after the initial render
if (!data) {
return <div>Loading...</div>;
}
return <div>Data: {JSON.stringify(data)}</div>;
}
In this example, useEffect fetches data from an API when the component mounts and updates the state with the fetched data.
Cleanup Function:
The function returned from the effect callback serves as a cleanup function, which React calls when the component unmounts or before the effect runs again. This is useful for tasks like unsubscribing from services or clearing timers.
javascript
CopyEdit
useEffect(() => {
const timer = setInterval(() => {
console.log('Timer running');
}, 1000);
return () => {
clearInterval(timer);
console.log('Timer cleaned up');
};
}, []); // Empty array means this effect runs once after the initial render
In this example, a timer is set up when the component mounts, and the cleanup function clears the timer when the component unmounts.
For a more in-depth explanation and additional examples, you can refer to the official React documentation on the useEffect hook.
100daysofcode lebanon-mug