Introduction
The useEffect hook in React allows you to perform side effects in function components. It replaces lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount in class components.
Basic Syntax
import React, { useState, useEffect } from 'react';
const Example = () => {
const [count, setCount] = useState(0);
useEffect(() => {
console.log(`Count updated: ${count}`);
});
return (
Count: {count}
);
};
export default Example;
Dependency Array
Adding a dependency array ensures that useEffect runs only when the specified value changes.
useEffect(() => {
console.log("This runs only when count changes");
}, [count]);
Cleanup Function
If your effect creates a subscription or event listener, use the cleanup function to remove it:
useEffect(() => {
const interval = setInterval(() => {
console.log("Interval running");
}, 1000);
return () => {
clearInterval(interval);
console.log("Interval cleared");
};
}, []);
Conclusion
The useEffect hook is essential for handling side effects in React function components. By understanding its behavior, you can efficiently manage state updates, subscriptions, and cleanup functions.
Labels
Development
