Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

74
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!