The useEffect hook in React allows you to perform side effects in function components. It can be used to synchronize state with external systems, such as APIs, timers, or even other state variables. Here's how it works with state:
-
Basic Usage: You can use
useEffectto run a function after the component renders. This function can access the current state and props. -
Dependency Array: You can specify a dependency array as the second argument to
useEffect. This array determines when the effect should run:- If you pass an empty array (
[]), the effect runs only once after the initial render. - If you pass an array with state variables, the effect runs whenever any of those variables change.
- If you pass an empty array (
-
Cleanup Function: You can return a cleanup function from the effect. This function runs before the component unmounts or before the effect runs again, allowing you to clean up resources (like timers or subscriptions).
Here's an example demonstrating how useEffect works with state:
import React from 'react';
const MyComponent = () => {
const [count, setCount] = React.useState(0);
const [message, setMessage] = React.useState('');
// Effect that runs whenever 'count' changes
React.useEffect(() => {
setMessage(`Count has been updated to ${count}`);
}, [count]); // Dependency array with 'count'
return (
<div>
<p>Count: {count}</p>
<p>{message}</p>
<button onClick={() => setCount(count + 1)}>Increment Count</button>
</div>
);
};
export default MyComponent;
In this example:
- The
useEffecthook updates themessagestate whenever thecountstate changes. - The effect runs after every render where
counthas changed, ensuring that the message reflects the latest count value.
