Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a problem in using hooks inside components?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading