React Training
  • React JS Library
  • Roadmap
  • Training OutLine
  • React js basics
    • Understanding React JS
    • React JS a framework?
    • Setting Up React
    • Say Hello to React
    • Everything is a Component
    • Create-react-app
  • React Building Blocks
    • JSX and Babel
    • One Way Data Flow
    • Virtual DOM
    • V of MVC
    • React Terminology
    • React Tooling
  • Day 01
    • Day 01 OutLine
    • All About JSX
    • React Tools/ npm & webpack
    • Introduction of Webpack
    • Hello world using webpack
      • Webpack Setting up with React
    • NPM Scripts | Package JSON
      • Package.json file
    • React JS Principles
      • One Way Data Flow
      • V of MVC
      • Virtual DOM
    • Create React App - Part-1
    • Create React App - Part-2
  • Day 02
    • Quick Recap
      • Quiz
    • State & Props
      • State & Props in Depth
      • State Vs Props | Compare
    • React LifeCycle Methods
      • React LifeCycle Methods for V-0.16 x
    • Constructor | Lifecycle
    • Write Flicker App | First App
  • Day 03
    • Quick Recap
    • Life Cycle Flow
      • Birth and Mounting
      • Initlization and Construction
      • Pre Mounting
      • Render Method
      • componentDidMount
    • Type of React Components
      • Examples- Quick Compare
      • Class and Functional components
      • Functional Components
    • YouTube application
      • Component Design
    • All in One LifeCycle
  • Assignment
    • React App development
  • Day 04
    • Quick Recap on Lifecycle
    • Lifecycle deprecated/New Methods
      • New Lifecycle Methods
    • Lets Build App Netflix | Mock
  • Assignment
    • Github battle App | Assignment
  • Day 05
    • Quick Recap : Hooks
    • ES6 Features | Hands-on
      • ES6 Code Examples
    • Next Stop - React Router | SPA
      • Code examples | Router
      • React Router Building Blocks
      • Application using react-router-dom
  • Day 06
    • Router V4 | Quick Recap
    • ES2015 | 16 Quick Recap
    • LifeCycle Methods -Part-1
    • LifeCycle Methods -Part-2
  • Day 07
    • Quick Recap | New Lifecycle
    • Quick Recap | React Routing
    • Context API | React JS
      • component with context APIs
      • Context API | examples
    • App using Hooks/Context APIs
  • Assignment
    • Assignments
  • State Management Day-08
    • Quick Recap
    • Managing React State
      • What is Redux
      • Understanding Redux
      • Hello World "Redux"
  • React Redux Day - 09
    • Redux State Manager
    • Redux Redux Development
    • Simple Application | Redux
  • Redux Live Application Day -10
    • Redux with existing Application
      • Redux with React App
      • Lets Build More Apps
      • Should I use Redux from Dan
    • Quick Look at JS in React
    • Learn By Reading
  • miscellaneous Items - Day 11
    • Hooks useReducer
    • Hooks useContext
    • Hooks useRef
    • Hooks useEffect
    • Hooks useState
    • Lazy Loading and code splitting
    • Styling React Component
  • React Next Step - Day 12
    • Topics
    • Jest and Enjyme Testing
    • Examples: Testing
  • React Native
    • What is React Native
    • Setting up Environment
      • Linux Systems
    • React Native Hello World App
    • React Native Architecture
    • React Native Vs Native
    • Expo Cli or React Native CLI
  • React Native core Fundamental
    • React Native "Hello World"
    • Course OutLine
    • Getting started with Expo App
    • Layout with Flexbox
    • Working with Styles and Events
    • Manging Component State and Props
    • Build Simple Task List Application
  • What to Debug & How to Debug
    • Debug React Native Application
Powered by GitBook
On this page
  • What are React lifecycle methods?
  • Common React Lifecycle Methods
  • Uncommon React Lifecycle Methods
  • React Component Lifecycle Diagram
  • Recap

Was this helpful?

  1. Day 02

React LifeCycle Methods

react Lifecycle Methods

What are React lifecycle methods?

You can think of React lifecycle methods as the series of events that happen from the birth of a React component to its death.

Every component in React goes through a lifecycle of events. I like to think of them as going through a cycle of birth, growth, and death.

  • Mounting – Birth of your component

  • Update – Growth of your component

  • Unmount – Death of your component

Now that we understand the series of lifecycle events let’s learn more about how they work.

Common React Lifecycle Methods

render()

The render() method is the most used lifecycle method. You will see it in all React classes. This is because render() is the only required method within a class component in React.

As the name suggests it handles the rendering of your component to the UI. It happens during the mounting and updating of your component.

Below is an example of a simple render() in React.

class Hello extends Component{
   render(){
      return <div>Hello {this.props.name}</div>
   }
}

As you can see in the example above, the render() method returns JSX that is displayed in the UI. A render() can also return a null if there is nothing to render for that component.

A render() method has to be pure with no side-effects.

React requires that your render() is pure. Pure functions are those that do not have any side-effects and will always return the same output when the same inputs are passed. This means that you can not setState() within a render().

You cannot modify the component state within the render().

If you do need to modify state that would have to happen in the other lifecycle methods, therefore keeping render() pure.

Furthermore, keeping your render() simple and clean without state updates makes your app maintainable.

componentDidMount()

Now your component has been mounted and ready, that’s when the next React lifecycle method componentDidMount() comes in play.

componentDidMount() is called as soon as the component is mounted and ready. This is a good place to initiate API calls, if you need to load data from a remote endpoint.

Unlike the render() method, componentDidMount() allows the use of setState(). Calling the setState() here will update state and cause another rendering but it will happen before the browser updates the UI. This is to ensure that the user will not see any UI updates with the double rendering.

You can modify the component state within the componentDidMount(), but use it with caution.

Caution: It is recommended that you use this pattern with caution since it could lead to performance issues. The best practice is to ensure that your states are assigned in the constructor(). The reason React allows the setState() within this lifecycle method is for special cases like tooltips, modals, and similar concepts when you would need to measure a DOM node before rendering something that depends on its position.

componentDidUpdate()

This lifecycle method is invoked as soon as the updating happens. The most common use case for the componentDidUpdate() method is updating the DOM in response to prop or state changes.

You can call setState() in this lifecycle, but keep in mind that you will need to wrap it in a condition to check for state or prop changes from previous state. Incorrect usage of setState() can lead to an infinite loop.

You can modify the component state within the componentDidUpdate(), but use it with caution.

Take a look at the example below that shows a typical usage example of this lifecycle method.

componentDidUpdate(prevProps) {
 //Typical usage, don't forget to compare the props
 if (this.props.userName !== prevProps.userName) {
   this.fetchData(this.props.userName);
 }
}

Notice in the above example that we are comparing the current props to the previous props. This is to check if there has been a change in props from what it currently is. In this case, there won’t be a need to make the API call if the props did not change.

componentWillUnmount()

As the name suggests this lifecycle method is called just before the component is unmounted and destroyed. If there are any cleanup actions that you would need to do, this would be the right spot.

You cannot modify the component state in componentWillUnmount lifecycle.

This component will never be re-rendered and because of that we cannot call setState() during this lifecycle method.

componentWillUnmount() {
 window.removeEventListener('resize', this.resizeListener)
}

Common cleanup activities performed in this method include, clearing timers, cancelling api calls, or clearing any caches in storage.

Uncommon React Lifecycle Methods

We now have a good idea of all the commonly used React lifecycle methods. Besides that, there are other lifecycle methods that React offers which are sparingly used or not used at all.

shouldComponentUpdate()

This lifecycle can be handy sometimes when you don’t want React to render your state or prop changes.

Anytime setState() is called, the component re-renders by default. The shouldComponentUpdate() method is used to let React know if a component is not affected by the state and prop changes.

Keep in mind that this lifecycle method should be sparingly used, and it exists only for certain performance optimizations. You cannot update component state in shouldComponentUpdate() lifecycle.

Caution: Most importantly, do not always rely on it to prevent rendering of your component, since it can lead to several bugs.

shouldComponentUpdate(nextProps, nextState) {
 return this.props.title !== nextProps.title || 
  this.state.input !== nextState.input }

As shown in the example above, this lifecycle should always return a boolean value to the question, “Should I re-render my component?”

static getDerivedStateFromProps()

This is one of the newer lifecycle methods introduced very recently by the React team.

This will be a safer alternative to the previous lifecycle method componentWillReceiveProps().

It is called just before calling the render() method.

This is a static function that does not have access to “this“. getDerivedStateFromProps() returns an object to update state in response to propchanges. It can return a null if there is no change to state.

This method also exists only for rare use cases where the state depends on changes in props in a component.

static getDerivedStateFromProps(props, state) {
    if (props.currentRow !== state.lastRow) {
      return {
        isScrollingDown: props.currentRow > state.lastRow,
        lastRow: props.currentRow,
      };
    }
    // Return null to indicate no change to state.
    return null;
  }

Keep in mind that this lifecycle method is fired on every render.

An example use case where this method may come in handy would be a <Transition> component that compares its previous and next children to decide which ones to animate in and out.

getSnapshotBeforeUpdate()

getSnapshotBeforeUpdate() is another new lifecycle method introduced in React recently. This will be a safer alternative to the previous lifecycle method componentWillUpdate().

getSnapshotBeforeUpdate(prevProps, prevState) {
    // ...
  }

It is called right before the DOM is updated. The value that is returned from getSnapshotBeforeUpdate() is passed on to componentDidUpdate().

Keep in mind that this method should also be used rarely or not used at all.

Resizing the window during an async rendering is a good use-case of when the getSnapshotBeforeUpdate() can be utilized.

React Component Lifecycle Diagram

Recap

  • React component lifecycle has three categories – Mounting, Updating and Unmounting.

  • The render() is the most used lifecycle method.

    • It is a pure function.

    • You cannot set state in render()

  • The componentDidMount() happens as soon as your component is mounted.

    • You can set state here but with caution.

  • The componentDidUpdate() happens as soon as the updating happens.

    • You can set state here but with caution.

  • The componentWillUnmount() happens just before the component unmounts and is destroyed.

    • This is a good place to cleanup all the data.

    • You cannot set state here.

  • The shouldComponentUpdate() can be used rarely.

    • It can be called if you need to tell React not to re-render for a certain state or prop change.

    • This needs to be used with caution only for certain performance optimizations.

  • The two new lifecycle methods are getDerivedStateFromProps()and getSnapshotBeforeUpdate().

    • They need to be used only occasionally.

    • Not many examples are out there for these two methods and they are still being discussed and will have more references in the futu

PreviousState Vs Props | CompareNextReact LifeCycle Methods for V-0.16 x

Last updated 5 years ago

Was this helpful?

The diagram below is from the showcasing the different React lifecycle methods and when they are invoked.

official React documentation