React.js - When To Use Each Lifecycle Method

Just a quick brain dump of my notes on React's lifecycle methods.


Mounting

componentWillMount

When does it hook:

  • Before initial render, both client and server (DOM does not exist yet).

What situations to use it:

  • Provides a way to set the component's initial state.

componentDidMount

When does it hook:

  • After the DOM has rendered.
  • Both the DOM and component have rendered when this function is called.

What situations to use it

  • When access to the DOM is needed.
  • A good place to set timers, AJAX requests.

Updating

These lifecyle methods will occur when parents change properties and then setState.

componentWillReceiveProps

When does it hook:

  • Runs just before new props are received.
  • Note: componentWillReceiveProps is not called on initial render.

What situations to use it:

  • Use it when props have changed and to setState before the component re-renders.

shouldComponentUpdate

When does it hook:

  • Runs before render and when new props or state are being received.
  • Note: shouldComponentUpdate is not called on initial render.

What situations to use it:

  • Use it to tweak the app's performance.
  • Sometimes props and state changes, but the component doesn't need to rerender (when it doesn't affect the DOM).
  • Return false to void unnecessary re-renders.

componentWillUpdate

When does it hook:

  • Immediately before rendering the component, after props or state have been received.
  • Note: componentWillUpdate is not called on initial render.

What situations to use it:

  • Prepare for a render update.
  • Note: setState can't be called in this function.

componentDidUpdate

When does it hook:

  • After component updates are rendered to the DOM.
  • Note: componentDidUpdate is not called on initial render.

What situations to use it:

  • Now that the component has been rendered, operations on the DOM can be done here.
  • Any DOM manipulations after an update.

Unmounting

componentWillUnmount

When does it hook:

  • Immediately before the component is removed from the DOM.

What situations to use it:

  • Cleanup of any event listeners etc.

Duncan Leung

Front End Developer at iHerb.com

Irvine, CA

Subscribe to Duncan Leung: Javascript and Front End Development

Get the latest posts delivered right to your inbox.

or subscribe via RSS with Feedly!