Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

227
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda