Skip to content

Instantly share code, notes, and snippets.

@littlemooon
Last active March 1, 2018 05:52
Show Gist options
  • Save littlemooon/568176a3e9e72eb4af4c3cc34f26efdf to your computer and use it in GitHub Desktop.
Save littlemooon/568176a3e9e72eb4af4c3cc34f26efdf to your computer and use it in GitHub Desktop.
Handy guide to react lifecycle methods

react lifecycle methods

constructor

DO

  • set initial state
  • if not using class properties syntax — prepare all class fields and bind functions that will be passed as callbacks

DON’T

  • cause any side effects (AJAX calls etc.)

componentWillMount

DO

  • update state via this.setState
  • perform last minute optimization
  • cause side-effects (AJAX calls etc.) in case of server-side-rendering only

DON’T

  • cause any side effects (AJAX calls etc.) on client side

componentWillReceiveProps(nextProps)

DO

  • sync state to props

DON’T

  • cause any side effects (AJAX calls etc.)

shouldComponentUpdate(nextProps, nextState, nextContext)

DO

  • use for increasing performance of poor performing Components

DON’T

  • cause any side effects (AJAX calls etc.)
  • call this.setState

componentWillUpdate(nextProps, nextState)

DO

  • synchronize state to props

DON’T

  • cause any side effects (AJAX calls etc.)

componentDidUpdate(prevProps, prevState, prevContext)

DO

  • cause side effects (AJAX calls etc.)

DON’T

  • call this.setState as it will result in a re-render
  • An exception to the above rule is updating the state based on some DOM property which can be only computed once a component has re-rendered

componentDidMount

DO

  • cause side effects (AJAX calls etc.)

DON’T

  • call this.setState as it will result in a re-render
  • An exception to the above rule is updating the state based on some DOM property which can be only computed once a component has re-rendered

componentWillUnmount

DO

  • remove any timers or listeners created in lifespan of the component

DON’T

  • call this.setState, start new listeners or timers
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment