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

146
Visualizações
React Native useState setInterval function not working properly

I am trying to display the countdown timer starting at 10, and decreasing down to 0 each second using setState and setInterval for RN.

My view is updating, but the timer is not working properly. It goes quite fast and skips around between 9 - 0 randomly. No errors are shown either within my code.

import { StyleSheet, Text } from 'react-native'
import React, {useState} from 'react'


export default function Timer() {

  // Countdown timer logic upon click event

  const [time, setTime] = useState(10)
  
    setInterval(() => {
      setTime(time => time > 0 ? time - 1 : time = 10)
    },1000)
  

  return (
    <Text style={styles.timer}>{time}</Text>
  )
}

const styles = StyleSheet.create({
  timer: {
    fontWeight: '700',
    fontSize: 24,
    color: '#00C261',
    fontFamily: 'Roboto',
    width: 30,
    textAlign: 'center',
    alignItems: 'center',
    justifyContent: 'center'
  }
})
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

As for now, you calling the interval on each render (check by logging in the interval), after few renders there is a "render race", instead try put the logic in dedicated hook so the interval will only called once.

Also notice the expression time = 10 returns 10 so your code works by mistake, you should treat the state as immutable.

export default function Timer() {
  const [time, setTime] = useState(10);

  useEffect(() => {
    const intervalID = setInterval(() => {
      setTime((time) => (time > 0 ? time - 1 : 10));
    }, 1000);

    return () => {
      clearInterval(intervalID);
    };
  }, []);

  return <Text style={styles.timer}>{time}</Text>;
}
about 4 years ago · Juan Pablo Isaza Relatório
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