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

78
Visualizações
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 Respostas
Responde à pergunta

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 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