react-hooks/exhaustive-deps
warnings when using useMemo
to try and prevent unnecessary re-rendering of the controls.
#393
-
In the first example, the buttons are dynamically created from an array. This is pretty obvious to the expert eye why the buttons are being recreated when the state changes. So, if I try to memoize the creation of the buttons. it works as intended and doesn't recreate the buttons every time the local state changes. const buttons = {}
useMemo(() => {
positions.forEach((p, i) => {
console.log('creating button ' + i)
buttons['button ' + i] = button(() => {
setTo(p)
})
})
}, [positions])
useControls('Camera', buttons) However, there is now the react warning "react-hooks/exhaustive-deps", despite my example now working as intended. So then to solve the const buttons = {}
useMemo(() => {
positions.forEach((p, i) => {
console.log('creating button ' + i)
buttons['button ' + i] = button(() => {
setTo(p)
})
})
}, [positions, buttons]) And then I get a different Ok, so then I do it, const buttons = useMemo(() => {}, [])
useMemo(() => {
positions.forEach((p, i) => {
console.log('creating button ' + i)
buttons['button ' + i] = button(() => {
setTo(p)
})
})
}, [positions, buttons]) Codesandbox : https://codesandbox.io/s/leva-test-4-lmhpey?file=/src/App.jsx So, all warnings are now gone, but if I run it, then I get I have tried all kinds of combinations to try and get this small demo to not recreate the buttons each time the state changes while also not having the I'm sure the answer is there, but I'm just unable to see it. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Hey @Sean-Bradley, a few observations:
However, here the solution to your problem is pretty obvious: const buttons = useMemo(() => {
const _buttons = {}
positions.forEach((p, i) => {
_buttons['button ' + i] = button(() => setTo(p))
})
return _buttons
}, [positions, setTo]) And if you're a fan of the reduce function: const buttons = useMemo(() => positions.reduce((acc, p, i) =>
Object.assign(acc, { [`button ${i}`]: button(() => setTo(p)) }), {}), [positions, setTo]) |
Beta Was this translation helpful? Give feedback.
Hey @Sean-Bradley, a few observations:
exhaustive-deps
lint rule in general, as long as you know what you're doing. We actually do that a lot in Leva 🤧However, here the solution to your problem is pretty obvious:
And if you're a fan of the reduce function: