React Component Lifecycle
Solution 1:
The key here is that Demo
is not unmounted. When you first render the app, it renders and mounts the Demo
component and passes the onChange
prop. But, when the callback is invoked from Demo it sets the state on App. Calling setState
in App doesn't unmount the Demo component, so there's no need to mount it again. When the component is mounted initially is when the constructor runs. If you had a toggle on the App component that would only show the component within render if a certain condition is true, that would trigger the component to unmount.
Check out this codesandbox and play around a little: https://codesandbox.io/s/lifecycle-methods-vivn6?file=/src/Lifecycle.js.
Also, this is a cool diagram to get a sense of what's happening: https://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/
The main key is that the constructor runs when the component mounts. It will only run again if the component is unMounted from the DOM and then remounted later.
Post a Comment for "React Component Lifecycle"