Skip to content

Declarative events in ReactJS

· 1 min read · react · javascript · frontend

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 : 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. RSS feed · LinkedIn

More writings

  1. Know When to Step In
  2. How to write an eval for your agent
  3. Your agent is probably using git worktrees
  4. So Much for O(1)
  5. We Might All Be AI Engineers Now
  6. The Hardest Bug I Ever Fixed Wasn't in Code
  7. Why I Switched to Podman (and Why You Might Too)
  8. The World is Stochastic
  9. Debugging a running Java app in Docker
  10. Why is it UTC and not CUT?
  11. Deep prop drilling in ReactJS
  12. Eigenvectors
  13. Java's fork/join framework
  14. TypeScript's omit and pick
  15. JavaScript's new immutable array methods
  16. Integrating JUnit 5 in Maven projects
  17. My take on ChatGPT and prompt engineering
  18. Positive Lookaheads
  19. Functors
  20. Fast forward videos with ffmpeg
  21. Rotate y-axis of a 2D vector
  22. Synchronizing time
  23. Vector rotation
  24. Sed find and replace
  25. Asgardeo try it application
  26. Flatten error constraints
  27. Good Git commit messages
  28. Asgardeo JIT user provisioning
  29. Monotonic Arrays
  30. How GOROOT and GOPATH works
  31. Two summation