Updated

If you want to handle pathological use cases inside React using JavaScript’s setInterval function, use this library called @use-it/interval developed by Donavon.

npm i @use-it/interval

Suppose you want to run a function periodically with a specified interval, but you need to control its behavior dynamically. Here’s how you can do it:

import useInterval from "@use-it/interval";
import { useState } from "react";

function Component() {
    const [play, setPlay] = useState(false);

    useInterval(() => {
        // do something periodically
    }, play ? 1000 * INTERVAL : null);

    // rest of your code ...
}

useInterval() example
In this example, clicking the play button periodically executes another procedure every 1 second to refresh this component in the background (blinks green). As soon as you click pause, it stops running that hook (idle state is gray).

Here’s the codesandbox demo for this.

Similarly, if you want to attach or detach event-handling logic to an element or global scope (like window or document) inside a React Hook, you can use @use-it/event-listener.

How convenient!

Reading list

Well, now what?

You can navigate to more writings from here. Connect with me on LinkedIn for a chat.