Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

108
Visualizações
React Strict mode causing unexpected behaviour

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.

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda