Component Lifecycle in ReactJS

Tram Ho

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 ()
  1. Always in 1 component
  2. Returns body as a div containing the component’s information (JSX language).
  3. Always called when there is a change
  • componentWillMount ()
  1. Called before render ()
  2. From props to compute state
  • componentDidMount ()
  1. Call immediately after render ()
  2. 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 ()
  1. Called before render ()
  2. Return true / false, default is false. Always run when updating state, the state to determine whether to update or not.
  • componentWillUpdate ()
  1. Called after shouldComponentUpdate ()
  2. Don’t call setState () in it
  3. Run right before render ()
  • componentDidUpdate ()
  1. 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 ()
  1. The function runs when the component receives a change of props passed in
  2. 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 ()
  1. Called when a component is removed from the DOM.
  2. Clear trash

Conclusion

Source Code

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!

Share the news now

Source : Viblo