How does useEffect work with state?

071

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:

  1. Basic Usage: You can use useEffect to run a function after the component renders. This function can access the current state and props.

  2. 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.
  3. 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 useEffect hook updates the message state whenever the count state changes.
  • The effect runs after every render where count has changed, ensuring that the message reflects the latest count value.

0 Comments

no data
Be the first to share your comment!