When a component is re-rendered in ReactJS, the following methods are called in order:
-
static getDerivedStateFromProps(nextProps, prevState): This static method is invoked right before calling the render
method. It is used to update the state based on changes in props. It returns an object to update the state, or null to indicate that the new props do not require any state updates.
-
shouldComponentUpdate(nextProps, nextState): This method is called before rendering when new props or state are being received. It allows you to control whether the component should re-render or not. By default, it returns true. If you want to optimize performance, you can implement custom logic here to prevent unnecessary re-renders.
-
render(): This is the only required method in a class component. It returns the JSX that represents the component's UI.
-
getSnapshotBeforeUpdate(prevProps, prevState): This method is called right before the changes from the virtual DOM are to be reflected in the actual DOM. It allows you to capture some information from the DOM before it is potentially changed (e.g., scrolling position). The value returned from this method is passed as a third parameter to the next method, componentDidUpdate
.
-
componentDidUpdate(prevProps, prevState, snapshot): This method is invoked immediately after updating occurs. It is not called for the initial render. Use it to perform any DOM operations or other side effects that rely on the updated DOM or to perform any cleanup.
This code outlines a typical React class component with the lifecycle methods in the order they're called during a re-render. Each method has comments explaining its purpose and when it's called.