pingeyeg
pingeyeg

Reputation: 680

Why is my clock code slowing my website down

I put together a basic clock to work with react hooks, but for some reason, kit really slows my website down. Any reason why that would be?

function Welcome() {
    const [time, setTime] = useState(new Date());
    setInterval(() => clock(), 1000);

    function clock() {
        setTime(new Date());
    }

    return (
        <WelcomeBox>
            <WelcomeTime>
                {date.toLocaleString('en-US', {
                    hour: 'numeric',
                    minute: 'numeric',
                    hour12: true,
                })}
            </WelcomeTime>
        </WelcomeBox>
    );
}

Upvotes: 0

Views: 111

Answers (2)

lowtex
lowtex

Reputation: 727

Don't start a timer every time the component renders

Instead, you should start the timer only once.

Use setTimeout instead of setInterval.

setTimeout waits the speficied amount of time, calls the callback, and goes away, while setInterval calls the callback over and over again with a delay between calls.

Here's an example

function Welcome() {
    // ...
    function clock() {
         setTime(new Date());
         setTimeout(clock, 1000);
    }
    // ...
}

Then you can call clock() once to start the clock.

Upvotes: 0

pteranobyte
pteranobyte

Reputation: 594

You are setting a new interval every time the component renders.

To properly do what I think you're trying to do, you need to put your setInterval inside a useEffect hook.

Like this:

function Welcome() {
    const [time, setTime] = useState(new Date());

    useEffect(() => {
        const interval = setInterval(() => clock(), 1000);
        return () => clearInterval(interval)
    }, [])

    function clock() {
        setTime(new Date());
    }

    return (
        <WelcomeBox>
            <WelcomeTime>
                {date.toLocaleString('en-US', {
                    hour: 'numeric',
                    minute: 'numeric',
                    hour12: true,
                })}
            </WelcomeTime>
        </WelcomeBox>
    );
}

Upvotes: 2

Related Questions