Component Lifecycle in ReactJS
What is it?
- Is the life cycle of a component
- A set of functions the react lib has built in
How is it defined?
With Components in React, Lifecycle consists of 3 phases:
- Mounting: Understand simply adding to the DOM, displayed on the user interface
- Updating: Processing process
- Unmouting: Understand simply leaving the DOM, hidden from the user interface
Mounting
- render ()
- Always in 1 component
- Returns body as a div containing the component’s information (JSX language).
- Always called when there is a change
- componentWillMount ()
- Called before render ()
- From props to compute state
- componentDidMount ()
- Call immediately after render ()
- Can interact with the user interface (setState)
You can see the console in the following image for a better visualization (it doesn’t matter the order in which the functions are defined)
Updating
The update functions are for state
- shouldComponentUpdate ()
- Called before render ()
- Return true / false, default is false. Always run when updating state, the state to determine whether to update or not.
- componentWillUpdate ()
- Called after shouldComponentUpdate ()
- Don’t call setState () in it
- Run right before render ()
- componentDidUpdate ()
- Manipulating UI
You can see the console in the following image for more visualization (Press CLICK button to perform update state):
Update functions are for props
- componentWillReceiveProps ()
- The function runs when the component receives a change of props passed in
- Call setSate () to render again
You can see the console in the following image for more visualization (Press CLICK button to do the change props passed in)
The rest of the other functions are exactly the same as when updating state
Unmouting
- componentWillUnmount ()
- Called when a component is removed from the DOM.
- Clear trash
Conclusion
Above is my general knowledge about the lifecycle of a component in reactjs. Of course, there will be no errors, hope readers comments to improve later. Thanks for reading the article.
Best regards!