7.2: Mounting Methods
A React Component kicks off the life cycle during the initial application ex: ReactDOM.render(). With the initialization of the component instance, we start moving through the mounting phase of the life cycle. The biggest focus of the mounting phase is the initial configuration for our Component instance. This is where we pass in the props, configure the default state and get access to the initial UI display. This also starts the mounting process for any children of the Component.
While the entire process of mounting is definitely worth knowing, we're going to get you started on the methods that you'll use most often when writing React applications.
Common Methods
render() *
The render()
method starts in the mounting phase and continues to exist in the update phases. One important thing to note about the render()
method is all it should be doing is rendering, do not have any calculations or anything in this method that will change the state or props. Do not call setState()
in render()
. Doing so will cause the render() method to trigger infinitely, as react re-renders on state change. Luckily, react is great about pointing problems like these out if you do unintentionally do this.
componentDidMount() *
The last step in the Mount life cycle phase is componentDidMount()
. This method is called once all of the component's children are mounted. Important to know is that componentDidMount()
is only called one time. Unlike our other Mount methods, where we start at the top and work down, componentDidMount()
works from the bottom up, starting from the children components and working upward. So by the time our parent component hits componentDidMount()
we know that children components have all gone through it as well.
Useful things to do in this life cycle method include:
Making API Calls (this is common and important to remember)
Initializing 3rd party libraries
Setting up listeners/subscriptions
Challenge
A helpful means of learning about life cycle components is writing console.log()
statements inside of the life cycle methods. You can do it like this:
In any case, start to learn the lifecycle methods by finding a way to step through some of the birthing and mounting lifecycle methods in the console so that you can see the order in which they are fired.
Last updated