Kaushal Khokhar
Kaushal Khokhar

Reputation: 43

Can we add variable as a dependencies which is not part of useEffect?

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?

Upvotes: 4

Views: 4159

Answers (3)

Gianluca Casati
Gianluca Casati

Reputation: 3753

I recommend to follow the guidelines given by React documentation, and provide a dependency array properly.

Probably you could do something like the following:

useEffect(()=>{
  if (token) {
    history.push("/home")
  }
},[token, history])

An easy way to get hints is using the eslint-plugin-react-hooks official eslint plugin provided by React, see documentation here.

Notice also that usually, if you are using some imported stuff, like probably is history in your example, that will not change, so it is not necessary to add it to dependency array.

Upvotes: 1

Drew Reese
Drew Reese

Reputation: 202846

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.

  1. Trigger an effect after every render by not including a dependency array.

    useEffect(() => console.log('every render'));
    
  2. Trigger an effect only on mounting by including an empty dependency array.

    useEffect(() => console.log('on component mount only'), []);
    
  3. 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).

Upvotes: 5

ZealousWeb
ZealousWeb

Reputation: 1751

Yes, you definitely can. Any changes to that variable will trigger the useEffect.

Upvotes: 0

Related Questions