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

211
Visualizações
Basic Beginner React-Native State Question

Hello guys I just started learning React-Native and I have a question about state.

I was practicing this concept trying to make a button that shows how many times I've pressed it.

My plan was to make a variable called clicks which will increase by 1 each time I press it and set the clickState to clicks. This is my code.

    export default function App() {
  const [clickState, setClicks] = useState(0)
  let clicks = 0
  return (
    <View style = {styles.container}>
      <StatusBar style="auto" />
      <TouchableOpacity style={styles.button} onPress={()=>{setClicks(++clicks); console.log(clicks)}}>
        <Text>Clicks : {clickState}</Text> 
      </TouchableOpacity>
    </View>
  );
}

this is the console

But apparently something is wrong and my clicks value goes random between 1 and 2 each time I click it instead of increasing by 1.

So I was curious about what I was doing wrong and why the values don't increase as I expected. I would also be glad if you showed how you would implement it if there is a better way.

Thanks guys.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You only need to update clickState, no need of variable clicks. Also it won't rerender if we increment state value directly, so we should increment state by taking its previous state value like shown below

export default function App() {
  const [clickState, setClicks] = useState(0)
  return (
    <View style = {styles.container}>
      <StatusBar style="auto" />
      <TouchableOpacity style={styles.button} onPress={()=>setClicks(prevState => prevState + 1)}>
        <Text>Clicks : {clickState}</Text> 
      </TouchableOpacity>
    </View>
  );
}
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