Skip to content
Advertisement

Converting componentDidMount into useEffect

I am trying to learn React hooks, and trying to convert existing codebase to use hooks, but I am confused. Is it normal to set state inside useEffect? Would I be causing the dreaded infinite loop if I do so?

JavaScript

My original class based component:

JavaScript

Advertisement

Answer

It’s okey to set state inside useEffect as long as you don’t listen to changes of the same field inside dependency array. In your particular case you are calling useEffect only once (since you have passed an empty dependency array).

JavaScript

Also would be cool to add the second useEffect to listen to cart changes and keep the localStorage up-to-date.

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement