Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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

useEffect(() => {
    console.log(currentGuess, userSelectedNumber);
    if (currentGuess === userSelectedNumber) {
      onGameOver(rounds);
    }
  }, [userSelectedNumber, onGameOver,currentGuess,rounds]);

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

useEffect(()=>{
    setCurrentGuess(randNumberGeneratorBetween(1, 100, props.userSelectedNumber))

},[props.userSelectedNumber]);

Solution 2:

The useEffect hook causes the component to update whenever any of the values of the dependency array changes. Make sure the values you use to trigger that hook are in fact changing.

Solution 3:

You can elegantly trigger useEffect by supplying a timestamp on you navigation.navigate call

e.g.

// someComponent.tsx

navigation.navigate('Home', {
  showSubscriptionModal: true
})
// HomeScreen.tsxconst showSubscriptionModal = props.route.params?.showSubscriptionModal ?? falseuseEffect(() => {
  if(showSubscriptionModal) setIsShowingModal(true)
},[showSubscriptionModal])

will only fire once, while

// someComponent.tsx

navigation.navigate('Home', {
  showSubscriptionModal: true,
  updateTs: newDate()
})
// HomeScreen.tsxconst showSubscriptionModal = props.route.params?.showSubscriptionModal ?? falseuseEffect(() => {
  if(props.route.params?.showSubscriptionModal) setIsShowingModal(true)
},[showSubscriptionModal, props.route.params?.updateTs])

will fire every time you re-navigate to your screen via navigation.navigate()

Post a Comment for "'useeffect' Hook Only Fires Once?"