React 16.3 lifecycle
Changes
- componentWillMount
- componentWillReceiveProps
- componentWillUpdate
UNSAFE lifecycle
NEW lifecycle
- getDerivedStateFromProps
- getSnapshotBeforeUpdate
New lifecycle diagram
New lifecycle
New lifecycle
Common Misusages
componentWillMount
class Example extends React.Component {
componentWillMount() {
const {
fetchList,
} = this.props;
fetchList();
}
render() {
// render Component
}
}
componentDidMount
class Example extends React.Component {
componentDidMount() {
const {
fetchList,
} = this.props;
fetchList();
}
render() {
// render Component
}
}
componentWillMount will fire before "render" is called
Common Misusages
componentWillReceiveProps
class Example extends React.Component {
componentWillReceiveProps({
options,
fetchList,
}) {
if(options !== this.props.options) {
fetchList();
}
}
render() {
// render Component
}
}
componentDidUpdate
class Example extends React.Component {
componentDidUpdate({
options, // prevProps
}) {
if(options !== this.props.options) {
this.props.fetchList();
}
}
render() {
// render Component
}
}
- componentWillReceiveProps will fire before "render" is called
- async request in componentWillReceiveProps should move into componentDidUpdate
New Method
componentWillReceiveProps
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
showInfo: false,
}
}
componentWillReceiveProps({
btnClicked,
}) {
if(btnClicked !== this.props.btnClicked) {
this.setState({
showInfo: this.props.btnClicked,
});
}
}
render() {
// render Component
}
}
getDerivedStateFromProps
class Example extends React.Component {
static getDerivedStateFromProps({
btnClicked, // props
}, {
showInfo, // state
}) {
if (btnClicked !== showInfo) {
return {
showInfo: btnClicked,
};
}
return null;
}
render() {
// render Component
}
}
Some Examples
- 3QMF_QRCode_Platform (develop) - admin/containers/AppManagement/BannerList.jsx
- 3QMF_QRCode_Platform (mobile) - mobile/LightBoxHandler.js
getDerivedStateFromProps use case
Summary
- Don't do any async action before rendering (side effect)
- You probably don't need derived state
Docs
My gitbook about React:
https://travorlee.gitbook.io/react-learning/react-component-lifecycle
React Official - You Probably Don't Need Derived State
https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html
React 16.3 lifecycle
By Travor Lee
React 16.3 lifecycle
- 147