React Life Cycle
React is following a unidirectional data flow. This means data is going one way exactly. This is the basics of React. To work like this developers made react similar to functional programming. The key rule of functional programming is immutability. Which means can’t change.
So how the unidirectional data flow is working?
· State is working as a data store. It contains the data of a component.
· The view of a component is renders based on the state.
· When the view needs to change something on the screen, that value should be supplied from the state.
· To do this react provides setState() function. What it does is, once it called it makes a virtual DOM of the new state. Then it compares with the Real DOM (previous state). If there is a change, the change is added to the Real DOM and then adds the new state to the state data store.
· The data in the state data store changes, react will trigger a re-render with the new state which the view consumes and shows it on the screen.
This cycle will continue throughout the component's lifetime.
Because of that, we can’t directly modify a component’s state. It will not show an error but the change does not appear on the View.
But if we change, App will behave abnormally.
React re-render all components and sub-components every time setState() is called. When the render method is called it returns a new Virtual DOM structure of the component. React changes Real DOM nodes in your browser only if they were changed in the Virtual DOM and as little as needed.
- Images get from Unsplash and Internet