The useEffect
hook is one of the most powerful and commonly used hooks in React. It allows you to perform side effects in functional components, such as fetching data, subscribing to events, or manually changing the DOM. In this blog post, we'll explore the useEffect
hook in detail with different examples.
Basic Usage
The basic syntax of useEffect
is:
useEffect(() => {
// Side effect code here
}, [dependencies]);
The callback function passed to useEffect
is the side effect you want to perform. It will run after every render by default. You can also specify an array of dependencies as the second argument. If any of the dependencies change between renders, the effect will re-run.
Example 1: Fetching Data
One common use case of useEffect
is fetching data from an API. Here's an example:
import React, { 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));
}, []);
return (
<div>
{data ? (
<p>Data: {data}</p>
) : (
<p>Loading data...</p>
)}
</div>
);
}
Example 2: Subscribing to Events
You can also use useEffect
to subscribe to events, such as resizing the window:
import React, { useState, useEffect } from 'react';
function WindowSize() {
const [windowSize, setWindowSize] = useState({
width: window.innerWidth,
height: window.innerHeight
});
useEffect(() => {
const handleResize = () => {
setWindowSize({
width: window.innerWidth,
height: window.innerHeight
});
};
window.addEventListener('resize', handleResize);
return () => {
window.removeEventListener('resize', handleResize);
};
}, []);
return (
<div>
<p>Window Width: {windowSize.width}</p>
<p>Window Height: {windowSize.height}</p>
</div>
);
}
Example 3: Cleanup Function
It's important to clean up after your effects to avoid memory leaks. You can return a cleanup function from useEffect
to perform cleanup:
import React, { useState, useEffect } from 'react';
function Timer() {
const [count, setCount] = useState(0);
useEffect(() => {
const intervalId = setInterval(() => {
setCount(count => count + 1);
}, 1000);
return () => {
clearInterval(intervalId);
};
}, []);
return (
<div>
<p>Count: {count}</p>
</div>
);
}
Conclusion
The useEffect
hook is a powerful tool for managing side effects in React functional components. Whether you're fetching data, subscribing to events, or performing other asynchronous tasks, useEffect
provides a clean and efficient way to handle side effects in your React applications.
Experiment with different use cases and explore the flexibility of useEffect
to enhance the functionality and interactivity of your React components!