Home > other >  Is there a problem in using hooks inside components?
Is there a problem in using hooks inside components?

Time:05-28

I'm new to react and I have read many docs about this problem, but the correct way of using hooks isn't that clear to me.

Let's say I have my main < App /> and inside my app I'm using multiple useState hooks. Inside my app I'm also using a component called < Component />.

Inside this Component I'm using a couple of useEffect hooks, so there goes my question, is placing the useEffect hooks inside the Component file a good practice? If not, if you need to have a useEffect hook inside a Component how would you accomplish that?

CodePudding user response:

There is nothing wrong with using the useEffect hook inside any component in your app.

I am assuming you are referring to the problem where the use of useState and useEffect hooks can cause your component to render infinitely. This happens when you update the state inside the useEffect hook, and that hook either has

  • no dependencies, or
  • depends on the state that you just updated

To avoid this, simply make sure your effect does not depend on the state you are updating.

CodePudding user response:

Yes, your setup is just fine. This is the beauty of hooks, is that you can use them in any function component, and as many as you want!

  • Related