Start and stop timer button

Start and stop timer button

Creating a start/stop button in React typically involves managing a state variable to control the active status of an operation, such as a timer or animation.

Core Concept

Demo implementation

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

export default function Timer() {
    const [seconds, setSeconds] = useState(0);
    const [isRunning, setIsRunning] = useState(false);
    const intervalRef = useRef(null); // To store the interval ID

    useEffect(() => {
        if (isRunning) {
            intervalRef.current = setInterval(() => {
                setSeconds(prevSeconds => prevSeconds + 1);
            }, 1000);
        } else {
            clearInterval(intervalRef.current);
        }

        // Cleanup function to clear the interval when the component unmounts or isRunning changes
        return () => clearInterval(intervalRef.current);
    }, [isRunning]); // Re-run effect when isRunning changes

    const handleStart = () => {
        setIsRunning(true);
    };

    const handleStop = () => {
        setIsRunning(false);
        // Optionally reset seconds when stopping
        // setSeconds(0);
    };

    return (
        <div>
            <h1>Timer: {seconds}s</h1>
            {isRunning ? (
                <button onClick={handleStop}>Stop</button>
            ) : (
                <button onClick={handleStart}>Start</button>
            )}
        </div>
    );
}