The useEffect
hook in React allows developers to perform side effects in functional components. These side effects may include data fetching, subscriptions, or manually changing the DOM. In this blog post, we’ll explore how to use the useEffect
hook, covering its syntax, use cases, and examples.
Syntax
The useEffect
hook takes two arguments:
useEffect(() => {
// Side effect code here
}, [dependencies]);
- The first argument is a function containing the code for the side effect.
- The second argument is an optional array of dependencies. If provided, the effect will only re-run if any of the dependencies have changed.
Mounting, Updating, and Unmounting
The useEffect
hook can mimic the lifecycle methods of class components:
- Mounting: Runs after the component is rendered for the first time.
- Updating: Runs after every render.
- Unmounting: Runs before the component is removed from the UI.
import React, { useEffect } from 'react';
function MyComponent() {
useEffect(() => {
// Component Mounting
console.log('Component mounted');
return () => {
// Component Unmounting
console.log('Component unmounted');
};
}, []);
return <div>My Component</div>;
}
Example: Fetching Data
Let’s consider an example where we fetch data from an API when the component mounts:
import React, { useState, useEffect } from 'react';
function MyComponent() {
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 dependency array, runs only once after mounting
return (
<div>
{data ? (
<ul>
{data.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
) : (
<p>Loading...</p>
)}
</div>
);
}
export default MyComponent;
Cleanup Function
useEffect
also supports a cleanup function that runs when the component unmounts:
useEffect(() => {
// Side effect code here
return () => {
// Cleanup code here
};
}, [dependencies]);
This is useful for unsubscribing from subscriptions or cancelling network requests.
Conclusion:
The ‘useEffect
‘ hook is a powerful tool for managing side effects in React functional components. By understanding its syntax and lifecycle behavior, developers can efficiently handle asynchronous tasks, subscriptions, and more in their applications.