Search code examples
reactjsintervals

React setInterval inside useEffect


I created a very basic interval in React.

import React, {useState, useEffect} from 'react';

const Loading2 = () => {
    const [percentage, setPercentage] = useState(0);

    useEffect(() => {
        const timer = setInterval(() => {
            setPercentage((prevPerc) => {
                if(percentage === 99)
                    return 0
                return prevPerc+1
            })
        }, 1000);
        return () => clearInterval(timer);
    }, [percentage])

    return (
        <div>
            <span>{percentage}%</span>
        </div>
    )
}

export default Loading2;

At first, I implemented without the return () => clearInterval(timer); in my useEffect and it did not work. Does anyone know why I need to return a function that cleans the interval? Also, why does it need to be a function, not only clearInterval(timer)?

Thanks


Solution

  • React performs the cleanup when the component unmounts. The useEffect hook is built in a way that if we return a function within the method, it gets executed when the component unmounts. Effects run for every render and not just once. useEffect's clean-up runs after the next render, before the next useEffect..

    The clean-up function runs before the component is removed from the UI to prevent memory leaks. Additionally, if a component renders multiple times (as they typically do), the previous effect is cleaned up before executing the next effect.

    useEffect(() => {
      // This is the effect itself.
      return () => {
        // This is its cleanup.
      };
    });