I am using Next.js and have the following hook;
export function useStopwatch(defaultValue = 0) {
const [timer, setTimer] = useState(defaultValue)
const {set: startInterval, clear: stopInterval} = useInterval()
var offset = 0;
function delta() {
let now = Date.now()
let delta = now - offset;
offset = now
return delta
}
function update() {
setTimer(prev => prev+delta())
}
function start() {
offset = Date.now();
startInterval(update, 1)
}
function reset() {
stopInterval()
setTimer(0)
}
return { time: Round(timer/1000, 2), start, stop: stopInterval, reset }
}
export function useInterval() {
const [reference, setReference] = useState<number | undefined>()
function set(callback: () => void, delay: number) {
if (!reference) {
setReference(window.setInterval(callback, delay))
}
}
function clear() {
if (reference) {
clearInterval(reference)
setReference(undefined)
}
}
return { set, clear }
}
This code works as expected in the browser (strict mode off) when I display time (time acts as a stopwatch) from useStopwatch(), when I turn strict mode on from the config. the hook seems to take a while to update its state, meaning that the stopwatch will pause for a second or two before adding a few milliseconds to the stopwatch.
next.config.js
module.exports = {
reactStrictMode: true,
}
From what I can tell strict mode only effects development and it puts in place various checks to help you write cleaner/safer code. However with strict mode enabled the timer seems to update much slower. I have found that setTimer does trigger appropriately but the state isn't set as frequently.
Why is this?
I have checked the console and there are no warnings/errors.