I noticed that react’s exhaustive-deps line rule doesn’t always play nice with the setState function or when you abstract out customHooks.
For example, if I have a customHook like:
function useValidation(initialThings) {
const [needsValidation, setNeedsValidation] = useState(false);
const [thingsToValidate, setThingsToValidate] = useState<Things[]>(initialThings);
useEffect(() => {
debounceValidateThings(thingsToValidate);
}, [things, debounceValidateThings]);
return {
needsValidation,
setNeedsValidation,
thingsToValidate,
setThingsToValidate,
}
}
and I use it one of the setState functions outside of the hook:
const validationHook = useValidation(initialThings)
useEffect(() => {
// Add something to validate
validationHook.setThingsToValidate(newThings)
validationHook.setNeedsValidation(true)
}, [newThings]);
I noticed this returns a warning with exhaustive-deps. It suggest that I add the entire useValidation
to the depth which might causes excessive rerenders.
At the same time, it won't let me just add the setState calls: e.g. setThingsToValidate
or setNeedsValidation
It still recommends that:
- setState be added as a dep even though it doesn’t have to be (https://reactjs.org/docs/hooks-reference.html#usestate)
- it recommends the entire useX hook is added to deps instead of just useX.setState which causes unnecessary rerenders
Is there a way around this that doesn’t involve a lint warning? Or this there a paradigm here for abstracting out hooks that I’m missing??