Skip to content

Instantly share code, notes, and snippets.

@Ricaidito
Last active December 16, 2022 18:39
Show Gist options
  • Save Ricaidito/93c448c616289d66bee54eb2d4e3dd0d to your computer and use it in GitHub Desktop.
Save Ricaidito/93c448c616289d66bee54eb2d4e3dd0d to your computer and use it in GitHub Desktop.
Custom React hook with stopwatch behavior
import { useState, useEffect } from "react";
export const useStopwatch = () => {
const [time, setTime] = useState(0);
const [isRunning, setIsRunning] = useState(false);
useEffect(() => {
let interval;
if (isRunning) {
interval = setInterval(() => {
setTime(time => time + 1);
}, 1000);
}
return () => clearInterval(interval);
}, [isRunning]);
const toggleStopwatch = () => {
setIsRunning(isRunning => !isRunning);
};
const resetStopwatch = () => {
setTime(0);
setIsRunning(false);
};
return { time, isRunning, toggleStopwatch, resetStopwatch };
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment