React Lifecycle Methods — Mounting

Photo by Ivan Diaz on Unsplash

These methods are called in the following order when mounting a component on the DOM

  • constructor()
  • getDerivedStateFromProps
  • render()
  • componentDidMount()

What is happening with each method?

The constructor() method is called before anything else- it is called when the react component is first initiated. It is where we can set up initial values and initial state. The constructor method is called by React every-time we make a component. Below is an example of setting up a counter with the initial value of 0.

The getDerivedStateFromProps() method is called right before rendering elements in the DOM (or right before the render() method). This method is for rare use cases where state depends on changes in props over time.

The render() method is required in a class component and this is the method that outputs the HTML to the DOM. When it’s called, it examines props and state and returns one of the following: react elements, arrays and fragments, portals, string and numbers, booleans or null. The render() function should be pure.

The componentDidMount() method is called immediately after the component is mounted. It is where you run code that requires that the component is already in the DOM.

References

Lifelong Learner