An open API service indexing awesome lists of open source software.

https://github.com/donavon/use-interval

A custom React Hook that provides a declarative setInterval called useInterval.
https://github.com/donavon/use-interval

hooks react reactjs

Last synced: 6 months ago
JSON representation

A custom React Hook that provides a declarative setInterval called useInterval.

Awesome Lists containing this project

README

          

# @use-it/interval

A custom React Hook that provides a declarative `setInterval` called `useInterval`.

> New version 1.0 has been completely rewritten in TypeScript!

[![npm version](https://badge.fury.io/js/%40use-it%2Finterval.svg)](https://badge.fury.io/js/%40use-it%2Finterval)
[![All Contributors](https://img.shields.io/badge/all_contributors-4-orange.svg?style=flat-square)](#contributors)

This hook is an implementation of [Dan Abramov](https://github.com/gaearon)'s blog post
["Making setInterval Declarative with React Hooks"](https://overreacted.io/making-setinterval-declarative-with-react-hooks/).

## Installation

```bash
$ npm i @use-it/interval
```

or

```bash
$ yarn add @use-it/interval
```

## Usage

Here is a basic setup.

```js
useInterval(callback, delay);
```

### Parameters

Here are the parameters that you can use.

| Parameter | Description |
| :--------- | :------------------------------------------------------------------------------- |
| `callback` | A function that will be called every `delay` milliseconds. |
| `delay` | A number representing the delay in msecs. Set to `null` to "pause" the interval. |

### Return

This hook returns nothing.

## Example

Let's look at some sample code. Here is a `Counter` component that counts up every second.

```js
import React, { useState } from 'react';
import useInterval from '@use-it/interval';

const Counter = ({ delay = 1000 }) => {
const [count, setCount] = useState(0);

useInterval(() => {
setCount((currentCount) => currentCount + 1);
}, delay);

return

{count}

;
};

export default Counter;
```

## Live demo

You can view/edit the sample code above on CodeSandbox.

[![Edit demo app on CodeSandbox](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/2n542qnzr)

## License

**[MIT](LICENSE)** Licensed

## Contributors

Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):



Donavon West

💻 🚇 ⚠️ 💡 🚧 👀 🔧

Dan Abramov

💻 📝 🤔

Michael Sync

🐛

lin onetwo

💻 🐛

Daniel Lauzon

💻

This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!