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
- State Management: Utilize React's useState hook to maintain a boolean state variable (e.g., isRunning) that indicates whether the process is currently active.
- Conditional Rendering/Logic: Based on the value of isRunning, conditionally render the "Start" or "Stop" button, or execute different logic within your component.
- Event Handlers: Implement onClick handlers for the buttons to toggle the isRunning state.
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>
);
}