useEffect(()=>{ history.push("/home") },[token, history])
i.e Here token is not part of useEffect
but I want to add it as a dependencies of useEffect
.
Can I do this? If not then why?
Advertisement
Answer
useEffect(()=>{ history.push("/home"); }, [token, history]);i.e Here token is not part of useEffect but I want to add it as a dependencies of useEffect. Can I do this? If not then why?
Yes, you can include, or omit, any dependencies, or omit the entire dependency array.
It works fine but I thought we should only add variable which should be part of useEffect.
Take a look at the official docs, Rules of Hooks and Conditionally firing an effect, and note there is no rule or requirement that dependencies can be only values referenced within the hook’s callback.
Trigger an effect after every render by not including a dependency array.
useEffect(() => console.log('every render'));
Trigger an effect only on mounting by including an empty dependency array.
useEffect(() => console.log('on component mount only'), []);
Trigger an effect conditionally by including values in the dependency array you want the effect callback to run after update.
useEffect(() => { console.log('any time a, b, or c update'); // or d or e }, [a, b, c, d, e]);
React suggests you use the ESLint Plugin (eslint-plugin-react-hooks
) to help enforce the Rules of Hooks and makes dependency suggestions. Note though that these are just opinionated suggestions and when including more dependencies, or no dependencies (such as mounting effects) that this plugin will warn you. Note also that this is only a warning and not an error (a common misconception).