An article for Entry level React Developers with high level overview.
This is part of a series “React Lifecycle Methods for Class Components”
Lifecycle methods are series of methods that gets triggered throughout lifecycle of a component.
Mounting → Updating → Un-mounting
Error Handling
Mounting
The mounting phase refers to the phase during which a component is created and inserted to the DOM.
constructor -> getDerivedStateFromProps -> render -> componentDidMount
1. constructor
The constructor method is called before the component is mounted to the DOM. Initialize state and bind event handlers methods here.
const MyComponent extends React.Component {
constructor(props) {
super(props)
this.state = { points: 0 }
this.handleEvent = this.handleEvent.bind(this)
}
}
2. static getDerivedStateFromProps()
static getDerivedStateFromProps
is a new React lifecycle method as of React 17 designed to replace componentWillReceiveProps
.
It ensures that the state and props are in sync.
It takes in props
and state
...
static getDerivedStateFromProps(props, state) {
return {
points: 200 // update state with this
}
}
...
3. render()
To render elements to the DOM, e.g., returning some JSX
class MyComponent extends React.Component {
// render is the only required method for a class component
render() {
return <h1> Hurray! </h1>
}
}
4. componentDidMount()
Invoked after the component is mounted to the DOM. It lets user get DOM node from the component tree immediately after it’s mounted.
Updating
Whenever a change is made to the state
or props
of a React component, the component is re-rendered i.e. updated.
getDerivedStateFromProps -> shouldComponentUpdate -> render -> getSnapshotBeforeUpdate -> componentDidUpdate
1. static getDerivedStateFromProps()
It is invoked in both the mounting and updating phases.
2. shouldComponentUpdate()
Within this lifecycle method, you can return a boolean — true
or false
— and control whether the component gets re-rendered (e.g., upon a change in state or props).
Used for performance optimization measures.
Built-in React.PureComponent
to avoid re-render if the state
and props
don’t change.
3. render()
Render depends on the returned value from shouldComponentUpdate
, which defaults to true
4. getSnapshotBeforeUpdate()
This is called right after the render
method, just before the DOM is updated.
It gets passed the previous props and state as arguments.
It returns either a value or null.
It is to be used in conjunction with the componentDidUpdate
lifecycle method.
Example: In Chat window, after new child chat component gets added and auto scroll needs to happen especially when window size exceeds
getSnapshotBeforeUpdate(prevProps, prevState) {
return value || null // where 'value' is a valid JavaScript value
}
5. componentDidUpdate()
It receives the previous props and state as arguments.
Value returned from the getSnapshotBeforeUpdate
lifecycle method is passed as the third argument to the componentDidUpdate
method.
componentDidUpdate(prevProps, prevState, snapshot) {
}
Unmounting
componentWillUnmount()
It is invoked immediately before a component is unmounted and destroyed. This is the ideal place to perform any necessary cleanup such as clearing up timers, cancelling network requests, or cleaning up any subscriptions that were created in componentDidMount()
Error handling lifecycle methods
static getDerivedStateFromError()
Whenever an error is thrown in a descendant component, this method is called first, and the error thrown passed as an argument.
static getDerivedStateFromError(error) {
console.log(`Error: ${error}`);
return { hasError: true };
}
componentDidCatch()
The componentDidCatch
method is also called after an error in a descendant component is thrown.
error and info is passed as arguments.
componentDidCatch(error, info) {
logToExternalService(error, info) // this is allowed.
//Where logToExternalService may make an API call.
}