Home > Software engineering >  ReactJS useEffect Hook - used more than once in a component?
ReactJS useEffect Hook - used more than once in a component?

Time:12-23

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!

CodePudding user response:

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 ]);

CodePudding user response:

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.

CodePudding user response:

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() { // 1.&text=Use an effect for persisting,; }); // 3.

  • Related