JAVASCRIPT

React `useCountdown` Hook for Simple Countdown Timers

Implement a flexible countdown timer in React, allowing developers to specify a starting time and easily manage its state, pause, reset, and check its completion.

import { useState, useEffect, useRef, useCallback } from 'react';

const useCountdown = (initialCount = 60) => {
  const [count, setCount] = useState(initialCount);
  const [isRunning, setIsRunning] = useState(false);
  const intervalRef = useRef(null);

  const start = useCallback(() => setIsRunning(true), []);
  const pause = useCallback(() => setIsRunning(false), []);
  const reset = useCallback(() => {
    setIsRunning(false);
    setCount(initialCount);
  }, [initialCount]);

  useEffect(() => {
    if (isRunning && count > 0) {
      intervalRef.current = setInterval(() => {
        setCount((prevCount) => prevCount - 1);
      }, 1000);
    } else if (count === 0) {
      setIsRunning(false);
      if (intervalRef.current) {
        clearInterval(intervalRef.current);
      }
    }

    return () => {
      if (intervalRef.current) {
        clearInterval(intervalRef.current);
      }
    };
  }, [count, isRunning]);

  return {
    count,
    isRunning,
    start,
    pause,
    reset,
    isFinished: count === 0
  };
};

export default useCountdown;
How it works: The `useCountdown` hook provides state and controls for a simple timer that counts down from an `initialCount`. It manages the countdown's active status (`isRunning`), offers functions to `start`, `pause`, and `reset` the timer, and automatically stops when the count reaches zero, leveraging `setInterval` with proper cleanup to prevent memory leaks. It's perfect for 'time remaining' displays.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs