Answer the question
In order to leave comments, you need to log in
Is it possible to not specify the function obtained from the hook in the useEffect dependencies?
There is a custom hook
const { doSomething } = useDoSomething()
and there is a useEffect that uses this hook
useEffect(() => {
doSomething({ type: 'run' })
}, [])
Answer the question
In order to leave comments, you need to log in
Rewrite your custom hook to return a constant function. Yes, with the same useCallback. If this hook does not depend on props / state, then obviously the function should be constant.
Warnings for this and warnings that the system is not sure that you did not write what you had in mind.
useEffect without dependencies will be executed on the first render of the component and that's it; if you add something to the dependency (not doSomething), then the callback will be executed every time the dependencies change, BUT doSomething will be used from the first render, which will most likely lead to errors. It is by this logic that the linter operates according to the principle: everything that is used in the hook must be specified in the dependencies. And it works great until all the contributors of the project are adequate, the code is not bloated to tens (or even hundreds) of thousands of lines, and you can personally be sure that the doSomething function is really updated only when it needs to be re-called (that is, it is not updated).
I can guarantee you that if there are more than two people in the project, and you work on it in total more than ten thousand hours of pure time, then something in your project will definitely fall off, due to the fact that something was written in the dependencies that linter asked, but it shouldn't be there. But also in reverse. Specifically, in your case, it is better not to expand the list of dependencies. but each time you write / change a hook, you need to think separately.
I’ll tell you one case, I had a component with hooks, everything is fashionable, one of the third-party hooks was used in useEffect and constantly changed its state, which caused a rerender, according to eslint rules, it should have been specified in deps, but when specified, the application went into endless reload.
Having indicated in the eslint comment that I myself decide what to add here, I got rid of the problem.
// eslint-disable-next-line react-hooks/exhaustive-deps
Get your own hook for such cases, like:
const useMounted = (callback) => useEffect(callback, []);
This will not fix the root of the problem, but in this particular case, that's it. Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question