# Declarative events in ReactJS

> Explore how to handle pathological events declaratively in ReactJS applications.

March 9, 2023 · 1 min read · https://yasint.dev/declarative-events-in-reactjs/
Tags: 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`](https://www.npmjs.com/package/@use-it/interval) developed by [Donavon](https://github.com/donavon).

```bash terminal
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:
```js

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

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

    // rest of your code ...
}
```

![useInterval() example](./interval.gif "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](https://codesandbox.io/s/use-it-interval-g1gocz) 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`](https://www.npmjs.com/package/@use-it/event-listener).

How convenient!

### Reading list

- [Dan Abramov's article about `setInterval`](https://overreacted.io/making-setinterval-declarative-with-react-hooks/)
- [Pathological (Mathematics)](https://en.wikipedia.org/wiki/Pathological_(mathematics))
- [Twitter thread by Donavon](https://twitter.com/donavon/status/1093612936621379584)
