Notes on React Lifecycle Methods
June 19, 2018
A living distillation of all React lifecycle recommendations I have encountered. Mostly, but not all, from the React core team at Facebook.
Intended as quick reference usage notes, not a duplicate of the descriptions of these methods in the official docs.
Notes are organized to mirror the modern React lifecycle diagram Dan Abramov tweeted in April 2018. All sources are annotated so you can fact-check me.
Render Phase
Pure and has no side effects. May be paused, aborted or restarted by React.
getDerivedStateFromProps
Most components do not need getDerivedStateFromProps
- Should be a pure function of props and state
- No manual DOM mutations here
- Do not assume it only fires on prop changes
- The three use cases for getDerivedStateFromProps are:
- Memoization. We have a better model for how this should work in the future.
- Avoiding the need to derive the same value repeatedly in multiple methods/lifecycles. (Similar to the problem that defaultProps solves.) Again, our future model handles this better.
- Reacting to prop changes. This is the weird one, and I don’t think we totally understand yet what the best practices should be.
- See https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html for an in-depth treatment.
render
- should be a pure function of props and state
Pre-Commit Phase
Can read the DOM.
getSnapshotBeforeUpdate
Commit Phase
Can work with DOM, run side effects, schedule updates.
componentDidMount
- manual DOM mutations belong here or inside
componentDidUpdate
componentDidUpdate
- manual DOM mutations belong here or inside
componentDidMount - careful with setState here—could trigger an infinite loop
componentWillUnmount
I'm Trevor Farlow, a Denver-based software developer. They said "always be learning," so here I am.