Skip to content

Instantly share code, notes, and snippets.

@meg-gutshall
Last active May 28, 2021 19:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save meg-gutshall/c1246e5f5abe58e169a843dbe68db059 to your computer and use it in GitHub Desktop.
Save meg-gutshall/c1246e5f5abe58e169a843dbe68db059 to your computer and use it in GitHub Desktop.

React Lifecycle Methods

Mounting Lifecycle Methods

Called once on initial render

Method current props and state prevProps prevState nextProps nextState Can call this.setState Called when? Used for
constructor no no no no no no once, just before static getDerivedStateFromProps() is called for the first time setting initial state
static getDerivedStateFromProps()* yes no no no no no right before the initial render and all re-renders not used often
render() yes no no no no no every time React updates and commits to the DOM writing JSX for components
componentDidMount yes no no no no yes once, just after mounting seting up side effects (e.g. creating new DOM elements or setting up asynchronous functions)

Updating Lifecycle Methods

Not called on initial render, but always called whenever a subsequent re-render is triggered

Method current props and state prevProps prevState nextProps nextState Can call this.setState Called when? Used for
static getDerivedStateFromProps()* yes no no no no yes before every render not used often
shouldComponentUpdate yes no no yes yes yes before every re-render (not initially) can be used to stop unnecessary re-renders for performance optimization
getSnapshotBeforeUpdate yes yes yes no no yes just before React updates and commits new content to the DOM used rarely; can capture data that may be changing rapidly
componentDidUpdate yes yes yes no no yes just after a re-render has finished andy DOM updates following a render (mostly interacting with third-party libraries)

Current props and state are always available through this.props and this.state. Some of these methods have access to previous props and state. In these cases, the props and state are being passed into the method by React.

Dismounting Lifecycle Method

Called only once, just before the component is removed from the DOM

Method current props and state prevProps prevState nextProps nextState Can call this.setState Called when? Used for
componentWillUnmount yes no no no no n/a once, just before component is removed from the DOM destroying any side effects set up in componentDidMount

*static getDerivedStateFromProps() is rarely called on initial render, but it can be

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment