
Bạn có thể check diagram này trên http://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/
Từ phiên bản 16.3 trở đi, React đã có lifecycle mới tuy nhiên vẫn hỗ trợ life cycle cũ.
Từ phiên bản 17 thì lifecycle cũ không được hỗ trợ nữa nên ở bài này chỉ để cập đến lifecyle hook mới của React.
Ở lifecycle cũ phát sinh nhiều vấn đề nhất là naming của lifecycle hook, gây hiểu nhầm!
Người ta thường dùng constructor, componentWillMount, comonentWillReceiveProps để init state dựa trên props, Vì vậy nhiều khi gây duplicate code. Đó là lý do mà getDerivedStateFromProps sinh ra để xoá sự khó hiểu và lằng nhằng đó đi.
Hoặc bạn muốn get thông tin nào đó của các ref trước khi render chẳng hạn, và sử dụng nó sau khi nó sau khi render lại.
Đó là lý do mà getSnapshotBeforeUpdate ra đời để thay thế componentWillUpdate, và componentDidUpdate có thêm một param mới là snapshoot.
Tóm lại lifecycle mới sẽ có dạng tóm tắt như sau:
Mounting: constructor → getDerivedStateFromProps → render → componentDidMount
Updating: getDerivedStateFromProps → shouldComponentUpdate → render → getSnapshootBeforeUpdate → componentDidUpdate
Unmouting: componentWillUnmount☆ contructor(props): void
Ví dụ:
class DemoComponent extends React.Component {
constructor(props) {
super(props)
this.state = {}
this.handleClick = this.handleClick.bind(this)
}
handleClick() {
this.setState({})
}
render() {
return <button onClick={this.handleClick}>Click</button>
}
}☆ static getDerivedStateFromProps(props, state): object
class DemoComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
fullName: `${props.lastName} ${props.firstName}`,
};
}
componentWillReceiveProps(nextProps, state) {
this.setState({ fullName: `${nextProps.lastName} ${nextProps.firstName}` });
}
...
}hoặc
class DemoComponent extends React.Component {
componentWillMount() {
this.setState({
fullName: `${this.props.lastName} ${this.props.firstName}`,
})
}
componentWillReceiveProps(nextProps, state) {
this.setState({ fullName: `${nextProps.lastName} ${nextProps.firstName}` })
}
}=> Khá là cực đúng không bạn?
Hãy chuyển sang lifecycle mới, nó sẽ trông như thế nào nhỉ?. Như này này:
class DemoComponent extends React.Component {
state = {}
static getDerivedStateFromProps(props, state) {
return {
fullName: `${props.lastName} ${props.firstName}`,
}
}
}☆ render(): ReactNode
☆ componentDidMount(prevProps, prevState): void
☆ static getDerivedStateFromProps(nextProps, state): object
☆ shouldComponentUpdate(nextProps, nextState): boolean
Note: Để thấy được sự khác nhau giữa PureComponent và Component, hãy vào link dưới: https://lecoder.io/component_types https://lecoder.io/component_vs_purecomponent
☆ render(): ReactNode
☆ getSnapshootBeforeUpdate(prevProps, prevState): object
☆ componentDidUpdate(prevProps, prevState, snapshoot): void
☆ componentWillUnmount: void
Nguồn tham khảo: https://github.com/nguyenvanhoang26041994/dev-experiences/blob/master/React/lifecyclehook_