I have this warning in my usage of Reacts useCallback hook.
React Hook useCallback has a missing dependency: 'history'. Either include it or remove the dependency array.eslint(react-hooks/exhaustive-deps
import { useHistory } from "react-router-dom";
const MyFunctionalComponent = () => {
const history = useHistory();
....
const someFunction = useCallback(((param) => {
history.push({
search: `?myParam=${param}`
});
....
}), [history]); <-- Putting history object here removes the warning...
return (
<Fragment>
<Something onClick={() => someFunction(myParam)}
</Fragment>
);
}
Putting history object in the useCallback dependecy param removes the warning, but make no sense to have it as a dependency for this method. This method does not depend on the state of history, it simply calls it method to update the history. Furthermore, i suspect that my parent component will rerender each time history changes, which defeats the purpose of using useCallback.
My question is how to use history object within my useCallback method:
- Without having the compiler warning (React Hook useCallback has a missing dependency: 'history'. Either include it or remove the dependency array.eslint(react-hooks/exhaustive-deps)
- Without putting a ignore statement for the warning (// eslint-disable-line react-hooks/exhaustive-deps)
- Without using window.history since this does not work well with the use of useLocation() hook. History change events are not triggered by window.history. Therefore, cannot use useEffect & useLocation hooks as per example in this article: https://reacttraining.com/blog/react-router-v5-1/?fbclid=IwAR1WHJKKeF0rO_-jW31mRCatWq5o143OvgyURn6R3uGlHNQ_dqs3QQ4ddLs