@seanred360
Posted
The useEffect error is a linting error. A linting error means your code will run but you used very bad practices. I think if you understood useEffect you would know how to fix it, let me explain. useEffect is a function that has 3 use cases. Case 1: useEffect(()=>{ doSomething() })
this will run on first render and then re run every time the component renders again. Case 2: useEffect(()=>{ doSomething() },[playerTurn, playerMark, gameActive, gameType])
this has a dependency array at the end of all the variables you used. useEffect will run once on first render and then run again every time one of these variables change. Case 3: useEffect(()=>{ doSomething() }, [])
the dependency array is empty here. useEffect will run once on first render and never again.
The linting error is telling you to either remove the dependency array, or move all your variables into the dependency array. Currently you have it set to only re run when playerTurn changes, but useEffect does not know it also needs to change when playerMark, gameActive, gameType change because you used them. If you put those variables into the dependency array, you app will infinitely re render and crash.
To fix your problem just remove the dependency array so that useEffect re runs on every render.
Look at my pull request on Github to see my fixes.
Marked as helpful
@seanred360 Thank you! I wanted useEffect to run again every time my playerTurn changes. Why do I have to add other states/variables to the dependency array (why can't I just use one variable)?
@seanred360
Posted
@fytrw You cannot only use playerTurn because your design ALSO uses other outside variables inside use Effect such as playerMark and game Active. If you use an outside variable in your use Effect you MUST include it in the dependency array. If you want to only run it when player turn changes, you need to refactor your code so that the only outside variable being used in useEffect is playerTurn, you could move your validation function and handleCPU function inside the useEffect, or find another way to do it without useEffect.
Here is why you shouldn't ignore the lint rule even though your code is currently working the way you want.
https://reactjs.org/docs/hooks-faq.html#is-it-safe-to-omit-functions-from-the-list-of-dependencies
Marked as helpful
@seanred360 Thanks a lot!