react-interval-hook

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

Usage no npm install needed!

<script type="module">
  import reactIntervalHook from 'https://cdn.skypack.dev/react-interval-hook';
</script>

README

: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>
    );
};

Options

Name Type Default Description
autoStart boolean true Start interval timer right after component is mounted
immediate boolean false Trigger callback immediately after timer is started
selfCorrecting boolean true Self correct time intervals between subsequent callback invocations to reflect actual time elapsed (setInterval and setTimeout are not accurate and tend to drift).
onFinish Function () => {} Called after timer is stopped (by stop method or component unmount)

Management methods

useInterval hook return object with various management methods

Name Arguments Return Description
start None void Starts timer when autoStart is set to false or after timer was stopped using stop method
stop [optional] triggerFinishCallback
- Type: boolean
- Default: true
void Stops timer (not pause) after it was started using either autoStart option or start method
isActive None boolean Return current timer status - is it running or not

License

MIT © minwork