React Component Lifecycle

Every component in React is reusable. As per the design of SPA, the specific templates or partial views are loaded in the browser whenever they are required. These views are components in React.

Every component in React has a lifecycle. What it means is that they are initiated to be rendered on the browser whenever they are needed, then they perform their duties and then they go away behind the scenes.

In React's terms, a component is rendered, performs its operation, updates itself several time during the course of its life and once its job is done, gets un-rendered.


A component during its lifecycle in React goes through 3 major phases:

  • Mount
  • Update
  • Unmount
Lets look at each phase closely.

  • Mount

    • This phase occurs when whenever an instance of a component is created and inserted into the DOM
    • Usually this happens when we initiate a component using constructor or render it directly.

  • Update
    • During the course of its lifetime, a component does activities designated to it.

    • A component can have its local state which it maintains and also might have some props passed down by its ancestors to deal with.

    • States and props might be used by component to compute its own state or even render something on the browser. So, whenever there is any change with component's state or props, it updates itself.

  • Unmount
    • Whenever role of a component is over, it is removed from the DOM.
    • This process of removal is called as unmount.
React provides us opportunities to get into component's lifecycle through few designated methods at each phase. These methods can be leveraged to perform any setup, manipulation or tear down activities.


  • Mount

    • In Mounting phase, we can leverage below methods to setup our initial states, values or even get data from HTTP resource and set to elements before render completes.
    • For class components, there are few frequently used methods which we can use:
      • constructor() 
      • render()
      • componentDidMount()

    • We have seen in our earlier examples how we can initialize default state values.

    • Please note that this phase occurs only once in the lifecycle of a component.

  • Update
    • This phase can occurs multiple times in a lifecycle of a component.

    • This can happen because of multiple reasons, such as user input, state updates by children, change in props because of changes in parent component etc. to name a few.

    • Please note that, whenever a state or props changes, a component is re-rendered.

    • For class components, there are 2 major methods:

      • render()

      • ComponentDidUpdate()

  • Unmount
    • This phase occurs when component is no longer needed and removed from the DOM.

    • For class components, frequently used method is:

      • componentWillUnmount()






 

Comments

Popular Posts