0
votes

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

1

1 Answers

0
votes

The way useEffect works is that : before executing the useEffect function after any render, it executes the function that was returned the last time this useEffect was called. If you return like this: return clearInterval(timer); you would have already executed the clearInterval function - it won't wait to be executed until the next render.