I am writing small Checkers project and ran out into a minor issue while trying to properly set a dependency array in useEffect. Take a look at this piece of code:
const BoardComponent = ({ board, setBoard }) => {
const [selectedSquare, setSelectedSquare] = useState<Square | null>(null)
// some logic...
// board - class instance with some methods which was put into the state
const updateBoard = () => {
const newBoard = board.getCopyBoard()
setBoard(newBoard)
}
const highlightSquares = () => {
board.highlightSquares(selectedSquare)
updateBoard()
}
useEffect(() => {
highlightSquares()
}, [selectedSquare])
}
I am getting this eslint warning:
Line 64:5: React Hook useEffect has a missing dependency: 'highlightSquares'.
Either include it or remove the dependency array react-hooks/exhaustive-deps
I was trying to solve this issue like this (code below) but faced infinite loop problem (which is not surprising, but i wanted to show that there might be a solution with proper usage of useCallback):
const updateBoard = useCallback(() => {
const newBoard = board.getCopyBoard()
setBoard(newBoard)
}, [board, setBoard])
const highlightSquares = useCallback(() => {
board.highlightSquares(selectedSquare)
updateBoard()
}, [board, updateBoard, selectedSquare])
useEffect(() => {
highlightSquares()
}, [selectedSquare, highlightSquares])
// output -> infinite loop!
Is there any chance to properly set dependecies array in useEffect (and, maybe use some useCallbacks) to get rid of this warning?