Home > OS >  useEffect is causing error because of variables?
useEffect is causing error because of variables?

Time:09-21

I just finished a project in react. But the only error that I couldn't solve was the function below:

useEffect(() => {
        if (guessedLetters.length 
            === uniqueLetters.length){
            
            startGame({ 
                score: score   points 
            })
        }
    }, [guessedLetters.length])

Error: React Hook useEffect has missing dependencies: 'points', 'score', 'startGame', and 'uniqueLetters.length'. Either include them or remove the dependency array react-hooks/exhaustive-deps

What would be the best way to solve this problem?

CodePudding user response:

Two ways to resolve this issue. But there maybe side-effects due to this. Side-effects include unnecessary re-rendering or no rendering at all.

First: Make the dependency array empty.

useEffect(() => {
        if (guessedLetters.length 
            === uniqueLetters.length){
            
            startGame({ 
                score: score   points 
            })
        }
    }, [])

Second: Include all the variables that you have used inside the use Effect.

useEffect(() => {
        if (guessedLetters.length 
            === uniqueLetters.length){
            
            startGame({ 
                score: score   points 
            })
        }
    }, [guessedLetters.length, uniqueLetters.length, points, score, startGame])

Alternatively, you can also use useCallback hook.

CodePudding user response:

useEffect(() => {
        if (guessedLetters.length 
            === uniqueLetters.length){
            
            startGame({ 
                score: score   points 
            })
        }
    }, [guessedLetters.length, points, score, startGame, uniqueLetters.length])

will get rid of the warnings, but you probably have a problem in the way your app mechanics are built if you're depending on so much stuff for the useEffect, the simple fact of adding the deps will probably introduce new bugs

  • Related