1.0.0 • Published 1 year ago

@zaki1001/react-interval v1.0.0

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

:watch: React Interval Hook

React hook for using self-correcting setInterval, augmented by management methods (start, stop, isActive)

Build Status codecov npm type definitions npm bundle size npm GitHub

  • Self-correcting (explanation)
  • Manageable (start, stop, isActive)
  • Thoroughly tested

Install

yarn add react-interval-hook

or

npm install --save react-interval-hook

Basic Usage

import React from 'react';
import { useInterval } from 'react-interval-hook';

const Example = () => {
    useInterval(() => {
        console.log('I am called every second');
    });
};

Advanced usage

Hook can accept various config option as well as return methods that allow you to control it behaviour.

Definition

useInterval(callback [, intervalMs] [, options]): { start, stop, isActive }

Example

Edit react-interval-hook

import React, { useState } from 'react';
import { useInterval } from 'react-interval-hook';

const AdvancedExample = () => {
    const { start, stop, isActive } = useInterval(
        () => {
            console.log('Callback every 500 ms');
        },
        500,
        {
            autoStart: false,
            immediate: false,
            selfCorrecting: false,
            onFinish: () => {
                console.log('Callback when timer is stopped');
            },
        }
    );
    const [active, setActive] = useState(isActive());
    const [triggerFinishCallback, setTriggerFinishCallback] = useState(true);

    return (
        <div>
            <button type="button" onClick={start} id="start">
                Start
            </button>
            <button type="button" onClick={() => stop(triggerFinishCallback)} id="stop">
                Stop
            </button>
            <button type="button" onClick={() => setActive(isActive())} id="checkActive">
                Check active
            </button>
            <div id="active">Active: {active ? 1 : 0}</div>
            <div>
                <label htmlFor="trigger-finish-callback">
                    <input
                        id="trigger-finish-callback"
                        type="checkbox"
                        defaultChecked={triggerFinishCallback}
                        onChange={() => setTriggerFinishCallback(current => !current)}
                    />
                    Trigger finish callback
                </label>
            </div>
        </div>
    );
};

Usage For React Class Based Components

Quickstart

Start counting on render

import { ReactInterval } from 'react-interval';

const App = React.createClass({
  getInitialState() {
    return {count: 0};
  },

  render() {
    const {count} = this.state;

    return (
      <div>
        {count}
        <ReactInterval timeout={1000} enabled={true}
          callback={() => this.setState({count: this.state.count + 1})} />
      </div>
    );
  }
});

Full example

Change timeout on the fly, start and stop counting

import React from 'react';
import ReactDOM from 'react-dom';
import { ReactInterval } from 'react-interval';

const App = React.createClass({
  getInitialState() {
    return {
      enabled: false,
      timeout: 1000,
      count: 0
    };
  },

  render() {
    const {timeout, enabled, count} = this.state;

    return (
      <div>
        <ReactInterval {...{timeout, enabled}}
          callback={() => this.setState({count: this.state.count + 1})} />

        <input type="number" step="200" min="200" max="5000" value={this.state.timeout}
          onChange={({target: {value}}) => this.setState({timeout: parseInt(value, 10)})} />&nbsp;

        <button disabled={enabled} onClick={() => this.setState({enabled: true})}>
          Start</button>&nbsp;

        <button disabled={!enabled} onClick={() => this.setState({enabled: false})}>
          Stop</button>&nbsp;

        {count}
      </div>
    );
  }
});

const appRoot = document.createElement('div');
document.body.appendChild(appRoot);
ReactDOM.render(<App />, appRoot);

Options

callback: PropTypes.func.isRequired

Function repeatedly called after timeout

enabled: PropTypes.bool (default: false)

Should start timer?

timeout: PropTypes.number (default: 1000)

Timeout before each callback call

Options

NameTypeDefaultDescription
autoStartbooleantrueStart interval timer right after component is mounted
immediatebooleanfalseTrigger callback immediately after timer is started
selfCorrectingbooleantrueSelf correct time intervals between subsequent callback invocations to reflect actual time elapsed (setInterval and setTimeout are not accurate and tend to drift).
onFinishFunction() => {}Called after timer is stopped (by stop method or component unmount)

Management methods

useInterval hook return object with various management methods

NameArgumentsReturnDescription
startNonevoidStarts timer when autoStart is set to false or after timer was stopped using stop method
stopoptional triggerFinishCallback- Type: boolean- Default: truevoidStops timer (not pause) after it was started using either autoStart option or start method
isActiveNonebooleanReturn current timer status - is it running or not

License

MIT © minwork