Skip to content

React Lifecycle Hooks Methods

sergio edited this page Jan 26, 2021 · 11 revisions

React Lifecycle

In order to enable this quick reacting and updating, as a developer, you get access to certain built-in events in the React component lifecycle called lifecycle hooks or lifecycle methods. These are opportunities for you to change how the component reacts (or doesn't react) to various changes in your app.

The only required method for a React component to be valid is the render() method which describes what the HTML for the component looks like. There are a whole host of optional methods you can use if you need more control over how the component responds to change.

Whenever a component's state or props are changed, it gets re-rendered on the page (Updating phase). That's the beauty of React components - they're quick to react to changes. Whenever a re-render is triggered, there is a whole host of lifecycle hooks that get called. You can choose to use any of these to decide how your React component should respond to changes.

Pre-Mounting:
  • constructor is called because each React Component is still just a JS class
Mounting:
  • static getDerivedStateFromProps called just before render, gives us access to any props and state. gets called every time a component renders. It is rarely used as logic before rendering impacts the performance. If you're comparing props from a parent to the state of a child, you can often avoid this by just putting the state in the parent component and handle the comparison logic in the parent.
  • render is invoked, most often returning JSX so that React can insert it into the DOM.
  • componentDidMount called just after the render method. Used for long-running processes or asynchronous processes such as fetching and updating data. better to render and display something even if not ready, once ready it can re-render and use the now ready API content.
Updating:
  • getSnapshotBeforeUpdate returns a 'snapshot' that can be used in the final update lifecycle method, componentDidUpdate. This snapshot allows us to capture things like scroll position, which can possibly change in the small amount of time before componentDidUpdate is invoked.
  • static getDerivedStateFromProps again available for rare situations where you may need to calculate state changes prior to an update.
  • shouldComponentUpdate invoked just before component re-render. To compare the old and new props and state and prevent unnecessary re-renders: if the changes in state/props don't actually alter the component, no point "repainting" it as it is an unnecessary performance drain.
  • render called, returns the JSX for React which uses it to figure out what to display on the page.
  • componentDidUpdate after the component is rendered and updated. It is possible in componentDidUpdate to take some actions without triggering a re-render of the component, such as focusing on a specific form input.
Unmounting:
  • componentWillUnmount only lifecycle hook at this stage, called just before the component gets deleted, to clear out any stuff set up in componentDidMount. For example, if you had a component that displays the weather data in your home town, you might have set it up to re-fetch the updated weather information every 10 seconds in componentDidMount. When the component gets deleted, you wouldn't want to continue doing this data-fetching, so you'd have to get rid of what was set up in componentWillUnmount.

The mounting and unmounting steps are important for ensuring that the React component gets set up and initialized nicely and that when it gets unmounted, it leaves the space it occupied just as it was before: nice and tidy.

In the mounting step, we can set up any special requirements we may have for that particular component: fetch some data, start counters etc. It is extremely important to clean up all the things we set up in the unmounting stage in componentWillUnmount, as not doing so may lead to some pretty nasty consequences - even as bad as crashing your carefully crafted application!

Mounting in Detail

static getDerivedStateFromProps

Is possible to use static getDerivedStateFromProps but is rarely used. It is called every time a component is rendered, including the first time. In the context of mounting, if your intention is to set an initial state for your component, it is preferable for you to do this in the constructor as this. If your intention is to set state using data from an async request, it is preferable that you do this in componentDidMount.

componentDidMount

componentDidMount is also only called once, but immediately after the first render() method has taken place. That means that the HTML for the React component has been rendered into the DOM and can be accessed if necessary. This method is used to perform any DOM manipulation or data-fetching that the component might need.

Suppose we were building a weather app that fetches data on the current weather and displays it to the user. We would want this data to update every 15 seconds without the user having to refresh the page. componentDidMount to the rescue!

componentDidMount() {
  this.interval = setInterval(this.fetchWeather, 15000);
}

Unmounting in Detail

componentWillUnmount is the only method in this phase and is to be called immediately before the component is removed from the DOM. It is generally used to perform clean-up for any DOM-elements or timers created in componentDidMount. In the previous weather API example it would be something like this:

componentWillUnmount() {
  clearInterval(this.interval);
}

clearInterval isn't other than a function created to get rid of the interval in this instance. clearInterval()

Updating in Detail

Clone this wiki locally