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) |
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.
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