I'm creating a custom hook and would like to define an optional param so that I can pass in extra dependencies when needed. My code looks like the following snippet:
import { useEffect } from 'react';
function useCustomHook(param1, extraDeps) {
useEffect(() => {
// do something with param1 here
}, [param1, ...extraDeps])
}
The react-hooks/exhaustive-deps throws a warning saying
React Hook useEffect has a spread element in its dependency array. This means we can't statically verify whether you've passed the correct dependencies
Anyone have an idea about how to address that warning? Or it's not a good practice to pass deps array to custom hook?
For those who are interested in why extraDeps is needed. here's an example:
const NewComponent = (props) => {
[field1, setField1] = useState()
[field2, setField2] = useState()
// I only want this to be called when field1 change
useCustomHook('.css-selector', [field1]);
return <div>{field1}{field2}</div>;
}
extraDeps. If the effect doesn't leverageextraDepsin some way, then it doesn't make sense for it to be part of the dependency array.extraDepsin my customHook. I addedextraDepsas an optional param so that when callinguseCustomHookwe can pass extra info into dependencies array to avoid unnecessary calls triggered by re-renders.state = { field1, field2, field3 }), If we want to trigger the hook only whenstate.field1changes, we need to passstate.field1as extraDeps to the custom hooks. So when I define the custom hooks, I can't determine what dependencies would be when the hook being used in a component.param1changes orstate.field1changes rather than only whenparam1changes. It would execute more not less.