I have this useEffect
hook:
useEffect(() => {
setTop(t => t + (controller.position.y * tileSize))
setLeft(l => l + (controller.position.x * tileSize))
}, [controller.position])
I want it to only do the addition if the position
changes. If the tileSize
changes I just want it to do the multiplication.
I tried putting it in two useEffect
but then I get the React Hook useEffect has missing dependencies
warning:
useEffect(() => {
setTop(t => t + (controller.position.y * spriteSize))
setLeft(l => l + (controller.position.x * spriteSize))
}, [controller.position])
useEffect(() => {
setTop((controller.position.y * spriteSize))
setLeft((controller.position.x * spriteSize))
}, [spriteSize])
What's the best practice in this case?
EDIT:
A reproducible example:
const [tileSize, setTileSize] = useState(0)
const controller = {
position: {
x: 0,
y: 0
}
}
useEffect(() => {
setTop(t => t + (controller.position.y * tileSize))
setLeft(l => l + (controller.position.x * tileSize))
}, [controller.position])
useEffect(() => {
setTop((controller.position.y * tileSize))
setLeft((controller.position.x * tileSize))
}, [tileSize])
const asdf = () => {
setTileSize(150)
}
return (
<div onClick={() => asdf()}>click me</div>
)
Warning message:
Line 31: React Hook useEffect has a missing dependency: 'tileSize'. Either include it or remove the dependency array. You can also replace multiple useState variables with useReducer if 'setTop' needs the current value of 'tileSize' react-hooks/exhaustive-deps
Line 36: React Hook useEffect has missing dependencies: 'controller.position.x' and 'controller.position.y'. Either include them or remove the dependency array react-hooks/exhaustive-deps Line 46: Unreachable code no-unreachable
[tileSize]
in seconduseEffect
hook? – DedaDevposition
in one of theuseEffect
hooks and then complain abouttileSize
in the other. – dan-klasson