498

useInterval

Hook that makes and interval and returns controlling functions

timehightest coverage
Hello
import { useInterval } from '@siberiacancode/reactuse';
import { useState } from 'react';

const GREETINGS = [
  'Hello',
  'Привет',
  'Hola',
  'Bonjour',
  'こんにちは',
  '你好',
  'Ciao',
  'Olá',
  'Hallo',
  'Salam'
];

const INTERVAL = 3000;

const Demo = () => {
  const [index, setIndex] = useState(0);

  useInterval(() => {
    setIndex((current) => (current + 1) % GREETINGS.length);
  }, INTERVAL);

  return (
    <section className='flex w-full max-w-md flex-col items-center gap-6 p-8'>
      <div key={index} className='animate-in fade-in slide-in-from-bottom-2 duration-500'>
        <span className='text-foreground text-5xl font-bold tracking-tight'>
          {GREETINGS[index]}
        </span>
      </div>

      <div className='bg-muted h-1 w-32 overflow-hidden rounded-full'>
        <div
          key={index}
          style={{
            animation: `progress ${INTERVAL}ms linear`
          }}
          className='bg-foreground h-full origin-left'
        />
      </div>

      <style>{`
        @keyframes progress {
          from { transform: scaleX(0); }
          to { transform: scaleX(1); }
        }
      `}</style>
    </section>
  );
};

export default Demo;

Installation

pnpm add @siberiacancode/reactuse

Usage

const { active, pause, resume, toggle } = useInterval(() => console.log('inside interval'), 2500);
// or
const { active, pause, resume, toggle } = useInterval(() => console.log('inside interval'), { interval: 2500 });

Type Declarations

export interface UseIntervalOptions {
  /** Start the interval immediately */
  immediately?: boolean;
}

export interface UseIntervalReturn {
  /** Is the interval active */
  active: boolean;
  /** Pause the interval */
  pause: () => void;
  /** Resume the interval */
  resume: () => void;
  /** Toggle the interval */
  toggle: () => void;
}

interface UseInterval {
  (callback: () => void, interval?: number, options?: UseIntervalOptions): UseIntervalReturn;

  (callback: () => void, options?: UseIntervalOptions & { interval?: number }): UseIntervalReturn;
}

API

Parameters

NameTypeDefaultNote
callback() => void-Any callback function
intervalnumber1000Time in milliseconds
options.immediatelybooleantrueStart the interval immediately

Returns

UseIntervalReturn

Parameters

NameTypeDefaultNote
callback() => void-Any callback function
options.intervalnumber1000Time in milliseconds
options.immediatelybooleantrueStart the interval immediately

Contributors

ddebabinEEksiartkkhmilevoi

Last updated on