Open In App

How do you use multiple useEffect in a component?

Last Updated : 21 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

useEffect is a hook used to perform side effects in function components. If you need to use multiple useEffect hooks in a single component, you can simply place them one after the other within your component function.

Key Points for Using Multiple useEffect Hooks:

  • Separation of Concerns: Each useEffect hook should handle a specific side effect or concern. This helps to keep your code organized and easier to understand.
  • Order Matters: The order in which you define useEffect hooks within your component matters. They will be executed in the same order as they are declared.
  • Dependency Arrays: Each useEffect can have its dependency array, which specifies when the effect should run. If the dependency array is empty ([]), the effect runs only once when the component mounts. If you provide dependencies, the effect runs whenever any of those dependencies change.
  • Dependencies Management: Be careful with dependencies to prevent unnecessary re-renders or side effects. Ensure that you include only the necessary dependencies for each useEffect hook.
  • Readability: Keep your code readable by placing each useEffect hook logically in relation to the component’s behavior. If one effect depends on another, consider placing them close together.

Example: Below is an example of using multiple useEffect in a component. The Timer component utilizes two useEffect hooks: one manages a timer based on the isActive state, while the other triggers an alert at 10 seconds, each with their specific dependencies, alongside functions to control the timer.

Javascript




import React, {
    useState,
    useEffect
} from 'react';
 
function Timer() {
    const [seconds, setSeconds] = useState(0);
    const [isActive, setIsActive] = useState(false);
 
    useEffect(() => {
        console.log("Timer isActive changed:", isActive);
        let intervalId;
        if (isActive) {
            intervalId = setInterval(() => {
                setSeconds((prevSeconds) =>
                    prevSeconds + 1);
            }, 1000);
        }
 
        return () => {
            console.log("Timer cleanup, isActive:",
                isActive);
            clearInterval(intervalId);
        };
    }, [isActive]);
 
    useEffect(() => {
        console.log("Timer seconds changed:",
            seconds);
        if (seconds >= 10) {
            alert('Timer reached 10 seconds!');
            setIsActive(false);
        }
    }, [seconds]);
 
    const startTimer = () => {
        setIsActive(true);
    };
 
    const stopTimer = () => {
        setIsActive(false);
    };
 
    const resetTimer = () => {
        setSeconds(0);
        setIsActive(false);
    };
 
    return (
        <div>
            <h2>Timer: {seconds} seconds</h2>
            <button onClick={startTimer}>Start</button>
            <button onClick={stopTimer}>Stop</button>
            <button onClick={resetTimer}>Reset</button>
        </div>
    );
}
 
export default Timer;


Output:

gfg40

Output



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads