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

217
Visualizações
Why is a value not updating correctly?

I am currently trying to teach myself react. I ran into this weird behavior and couldn't explain what was going on so I was hoping to get some answers.

In the below code snippet. I have a variable index that's initially set to 0. When I click the button, I expect handleClick() to update the value of index. However, it does not do it as I would expect.

const { useState } = React;
const Home = () => {
    
    let names = ["Hello", "World"];
    let index = 0;
    const [name, setName] = useState(names[index]);

    const handleClick = () => {
        console.log(`Output: ${name}`);
        console.log(`Index = ${index}`);
        index = (index+1)%2;
        setName(names[index]);
    }

    return (
        <div className="Home">
            <button onClick={handleClick}>Click</button>
        </div>
      );
}
 
ReactDOM.render(<Home />, document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>

I expect the console.log output to be as follows:

Output: Hello
Index = 0
Output: World
Index = 1
Output: Hello
Index = 0
Output: World
Index = 1
...

Instead, what I get is:

Output: Hello
Index = 0
Output: World
Index = 0
Output: World
Index = 1
Output: Hello
Index = 0
...

Can someone explain what is going on here?

about 4 years ago · Santiago Gelvez
3 Respostas
Responde à pergunta

0

When a state variable is updated using setState method, the component re-renders. In your code the index variable is not a state variable, so whenever the Home component re-renders the index variable will be inialized to 0.

You can change index to state variable or you can also use ref, if you what to persist its state accross re-renders.

about 4 years ago · Santiago Gelvez Relatório

0

You should consider moving the index to the state and moving names to props. The former will correct the behaviour of the component, as you're looking for, and the latter will make the component more re-usable.

const { useState } = React;
const Home = ({names}) => {
    
    const [index, setIndex] = useState(0);
    const name = names[index];

    const handleClick = () => {
        console.log(`Output: ${name}`);
        console.log(`Index = ${index}`);
        setIndex((index+1)%2);
    }

    return (
        <div className="Home">
            <button onClick={handleClick}>Click</button>
        </div>
      );
}
 
ReactDOM.render(<Home names={["Hello", "World"]} />, document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>

about 4 years ago · Santiago Gelvez Relatório

0

instead of just let index = 0

which is re-initialized to 0 every rerender when setName is run you need something which is not re-initialized, as below

//on your imports
import {useRef} from 'react'

//inside you component 
const index = useRef(0);

//on updating it
index.current = (index.current+1)%2
about 4 years ago · Santiago Gelvez 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