I’m working on my first project of the front end libraries certificate, and for the past day and a half I was stuck at the very beginning. I couldn’t update my state from outside the initial state initialization. After realizing the setState() method was the issue, I thought that maybe I didn’t have the right libraries/packages imported. I had the react-dom and react imported, but for some reason it still wasn’t working. I researched the version of react I was using (16.9.0 which is what gets imported when you type react into the search bar), and the documentation said that setState() causes an infinite loop when used from useEffect and componentDidUpdate. The next thing I did was go to the drum machine sample project provided by freeCodeCamp and copy and pasted what they imported and it started working fine. What I want to know is, is there a way to search for different versions of react libraries? Does anyone know the scope of the basic issues to look out for when using version 16.9.0?
So for example:
npm install --save email@example.com
The issue you are describing has always been present in react – you can now use hooks, so you are describing setting the value from
useState in a
useEffect hook, but exactly the same issue occurs if you update the state via
- a React component updates and rerenders when the state changes.
componentDidUpdatefire every time the component updates.
setStateor the setter for
useStateupdate the state.
- this updates the component, so
componentDidUpdatefire again and so on.
The documentation does not just say it causes an infinite loop – these functions are generally used for updating the state in some way, and everyone’s web apps are not stuck in infinite loops – it says it can cause an infinite loop unless you tell it to only update if the value you’re updating to is not the one already in the state.