When you have a hook that returns a function should you wrap the function in useCallback to make sure a new reference is not created unnecessarily?
My thought process is if that function was used by another hook in a dependency array, the new function reference would cause the 2nd hook to trigger even when nothing changes. Should a hook only change it's output when it had a reason to change, or is it alright if a hook is noisy?
function useExample(someParam) {
// ...
const onChange = () => { /*some operation*/ }
return { onChange }
}
function Component(props) {
const { onChange } = useExample(props)
useEffect(() =>
//Some action
, [onChange])
// ...
}
The useEffect hook, or rather, the react-hooks linting rule, can't possibly know the origin of the callback function returned from the other function other than that it sees only a function declared external to the useEffect hook.
The decision to memoize this callback is entirely up to you and the specific use case.
I'm assuming your actual use case isn't as trivial as an effect that only calls the callback, though, so there are probably other dependencies.
If the additional "noise" of the effect running each render cycle when callback is a new reference doesn't cause any undesirable then it is probably ok. Otherwise, yes, memoize the callback to provide a stable reference for the useEffect hook.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With