Is there a problem in using hooks inside components?

Viewed 45

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?

2 Answers

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.

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