Skip to content
Advertisement

‘useEffect’ hook only fires once?

I am working of a Guessing Game for ‘React Native’ where the user enters a number and the phone tries to guess it. Each time the phone generates a guess the user can click Greater/Lower. When the user entered number and the computer made guess equal each other we are taken to the game over screen.

The game over screen is not rendering. The logic to render the game over screen is placed inside of a useEffect()

Problem

useEffect is only fired once during the mounting phase and never again?

JavaScript

(./screens/GameScreen.js)

We should exit the GameScreen when currentGuess === userSelectedNumber but this code is only run once.

Full code for GameScreen below:

JavaScript

Project can be found here: https://codesandbox.io/s/github/SMasood1/guessingGame?file=/screens/GameScreen.js:852-1039

Advertisement

Answer

You need to add rounds and currentGuess to the dependencies array in the useEffect hook

JavaScript

Also it is considered a anti-pattern to use props to initialize a state, so I would recommend to add an other useEffect hook:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement