Miss any of our Open RFC calls?Watch the recordings here! »

@react-corekit/use-interval

1.1.1 • Public • Published

@react-corekit/use-interval

React Hook implementation for setInterval()

NPM JavaScript Style Guide

Install

npm install --save @react-corekit/use-interval
yarn add @react-corekit/use-interval

Syntax

useInterval(func, delay);

Parameters

func

A function to be executed every delay milliseconds. The function is not passed any arguments, and no return value is expected.

delay

The time, in milliseconds (thousandths of a second), the timer should delay in between executions of the specified function.

Usage

Visit: https://react-corekit.github.io/use-interval/ for a minimalistic live demo.

import React, { useState } from "react";
 
import { useInterval } from "@react-corekit/use-interval";
 
const Counter = () => {
  const [count, setCount] = useState(0);
 
  useInterval(() => {
    setCount(count + 1);
  }, 1000);
 
  return <h1>{count}</h1>;
};

Pausing and Reseting the counter example

const App = () => {
  const [delay] = useState(1000);
  const [count, setCount] = useState(0);
  const [isRunning, setIsRunning] = useState(true);
 
  useInterval(
    () => {
      setCount(count + 1);
    },
    isRunning ? delay : null
  );
 
  return (
    <div>
      <h1>{count}</h1>
      <button onClick={() => setCount(0)}>Reset</button>
      <button onClick={() => setIsRunning(!isRunning)}>
        {isRunning ? "Stop" : "Start"}
      </button>
    </div>
  );
};

Additional documentation

Window/GlobalScope setInterval Reference

Making setInterval Declarative with React Hooks

Credits

Based on Dan Abramov's post "Making setInterval Declarative with React Hooks".

License

MIT - glongh

Install

npm i @react-corekit/use-interval

DownloadsWeekly Downloads

9

Version

1.1.1

License

MIT

Unpacked Size

442 kB

Total Files

23

Last publish

Collaborators

  • avatar