Changes
UNSAFE lifecycle
NEW lifecycle
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
}
}
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
}
}
getDerivedStateFromProps use case
Summary
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