Elcid_91
Elcid_91

Reputation: 1681

ReactJS useEffect Hook - used more than once in a component?

I've searched for an answer to this question but I can see to find what I need. In a single component, can useEffect() be used more than once?

For Example:

export const MyDataForm = (props) => {
    ...    
    useEffect(()=>console.log(var1),[var1]);
    useEffect(()=>console.log(var2),[var2]);
    return (<></>);
}   

Is this legal, recommended, not recommended? Thanks!

Upvotes: 1

Views: 325

Answers (3)

snazzyy
snazzyy

Reputation: 151

Simply - yes, you can use as many useEffects as you want.

Given you have individual deps for each hook you likely should be seperating the logic.

I didn't see anything in the React docs but they do speak about using multiple useEffect and useState hooks [here][1] if that gives you a little more confidence you're doing the right thing.

Personally I've use multiple useEffect hooks both in personal projects and in a professional environment.

[1]: https://reactjs.org/docs/hooks-rules.html#:~:text=Explanation,Form()%20%7B%20%2F%2F%201.&text=Use%20an%20effect%20for%20persisting,%3B%20%7D)%3B%20%2F%2F%203.

Upvotes: 0

BenM
BenM

Reputation: 53238

Yes, it is permitted, and recommended depending upon your use case.

useEffect() allows your component to subscribe to changes to a specific state. The dependencies you pass in the array of the second argument are those you wish to subscribe to within the callback. It doesn't make sense to subscribe to all of them in a single useEffect().

For instance, let's say you have a user and invoices state variable coming from your Redux store. You may wish to perform an action when user changes, but not when invoices does, and conversly when invoices changes but not user. If you add both of these entities to the dependency array of a single useEffect() hook, the callback when will be executed when either of the entities changes, not both of them. This can lead to unnecessary re-renders.

You should add two separate useEffect() hooks to achieve this, for example:

useEffect(() => { 
   // Executed when user changes
}, [ user ]);

useEffect(() => { 
    // Executed when invoices changes
}, [ invoices ]);

useEffect(() => {
    // Executed when either user OR invoices changes
}, [ user, invoices ]);

Upvotes: 1

If it makes sense, there's no problem in using useEffect more than once. Especially in your case where you have different dependencies for each hook.

Upvotes: 1

Related Questions