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

77
Vistas
React useState Dependency Won't Update When Same Value Passed

I'm trying to create a game using React hooks. Essentially you get given a football players career history and you have to guess which player it is.

I'm having an issue though, because on rare occasions you might guess a player for e.g 'beckham' and then the next player generated may have the same name 'beckham' but be a completely different player just ironically has the same name.

My issue is I have a useEffect with a dependency of guess e.g 'beckham' and then some code runs to check the answer.

But if you have a player with an indentical surname again on the next player and guess 'beckham' again then the check answer code never runs because the useEffect looks at the guess dependency and says it's the same as before I'm not running the code inside.

Codepen example

https://codepen.io/joe-consterdine/pen/popmNrE

Here the useEffect will never rerender because 'joe' is always the guess, but in the game there's two joes so it's not the same person.

Thanks

  const [players, setPlayers] = React.useState([
    {
      id: 0,
      name: 'joe'
    },
    {
      id: 2,
      name: 'joe'
    },
  ]);
  const [guess, setGuess] = React.useState('joe');
  
  const handleOnSubmit = (event) => {
    event.preventDefault();
    // setGuess('james');
    setGuess('joe');
  }
  
  React.useEffect(() => {
    console.log('re rendered');
  }, [guess])

  return (
    <div>
      <form onSubmit={handleOnSubmit}>
        <input type="text" />
        <button type="submit">Submit</button>
      </form>
      {players.map(player => (
          <p key={player.id}>{player.name}</p>
      ))}
    </div>
  );
}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I would change the string state with object state. With this solution you will not have same problem

const [guess, setGuess] = React.useState({id: 0, name: 'joe'});
about 4 years ago · Juan Pablo Isaza 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