Skip to content
1 min read

Declarative events in ReactJS

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

Thanks for reading.

Say hi on LinkedIn (opens in new tab)

More writings

  1. 2026 4

    1. So Much for O(1)
    2. We Might All Be AI Engineers Now
    3. The Hardest Bug I Ever Fixed Wasn't in Code
    4. Why I Switched to Podman (and Why You Might Too)
  2. 2024 3

    1. The World is Stochastic
    2. Debugging a running Java app in Docker
    3. Why is it UTC and not CUT?
  3. 2023 12

    1. Deep prop drilling in ReactJS
    2. Eigenvectors
    3. Java's fork/join framework
    4. TypeScript's omit and pick
    5. JavaScript's new immutable array methods
    6. Integrating JUnit 5 in Maven projects
    7. My take on ChatGPT and prompt engineering
    8. Declarative events in ReactJS
    9. Positive Lookaheads
    10. Functors
    11. Fast forward videos with ffmpeg
    12. Rotate y-axis of a 2D vector
  4. 2022 9

    1. Synchronizing time
    2. Vector rotation
    3. Sed find and replace
    4. Asgardeo try it application
    5. Flatten error constraints
    6. Good Git commit messages
    7. Asgardeo JIT user provisioning
    8. Monotonic Arrays
    9. How GOROOT and GOPATH works
  5. 2021 1

    1. Two summation