It is important to understand the lifecycle of an React component. You can attach the handler to each React Lifecycle. It is useful to set initial states or other tasks at the right moment.
The life cycle of the component when you have an “App” component
- JS file is loaded by a browser.
- An instance of the “App” component is created.
- The “constructor” function is called.
- — Object state is created and assigned to the “this.state” property.
- — “this.state” can be initialized.
- React calls the “render()” method.
- “App” component returns JSX and gets rendered as HTML.
After that, the state can be changed.
- New data is available.
- The state object is updated by the “this.setState()” call
- React recognizes that the state is updated.
- React calls the “render()” method again.
- “App” component returns new JSX and updates the content in HTML.
Lifecycle Methods – Mounting phases
Each Lifecycle method is called while the component is rendered or to be removed.
- constructor: In this stage, you can initialize states.
- Good place for the one-time initial setup
- render: The component is rendered here.
- Avoid anything except constructing the JSX output
- componentDidMount: It is called just after the component is mounted (after the component is rendered for the first time).
- Good place for the data loading, such as initiating network updates, and calling the “setState()” method.
constructor(props) {
}
render() {
}
componentDidMount() {
}
Lifecycle Methods – Updating phases
There are other lifecycle methods that you consider while the component is updated.
- shouldComponentUpdate: It indicates if a component’s output is not affected by the current change in state or props (true – default – or false)
- render:
- componentDidUpdate: It is invoked immediately after updating occurs. This method is not called for the initial render.
- Good place for the additional data modification based on the props/state changes
shouldComponentUpdate(nextProps, nextState) {
}
render() {
}
componentDidUpdate(prevProps, prevState, snapshot) {
}
Lifecycle Methods – Unmounting phases
- componentWillUnmount:
- Good place for the non-React cleanups
componentWillUnmount()
Lifecycle Methods – Example
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
message: 'My App'
};
setTimeout(() => {
this.setState( prev => {
return {message: `${prev.state} - Updated.`};
});
}, 2000); // after 2 seconds
}
componentDidMount() {
console.log('componentDidMount');
}
componentDidUpdate(prevProps, prevState) {
console.log('componentDidUpdate');
console.log(prevState);
console.log(this.state);
}
render() {
console.log('render');
return (
<div>
{this.state.message}
</div>
);
}
}
