lifecycle_methode
lifecycle_methode
methods in
class
components
Mounting :-
When the component is being created and inserted into
the DOM
1. constructor(props):
o Called when the component is initialized.
o Useful for setting up initial state or binding methods.
o Always the first method called.
constructor(props) {
super(props);
this.state = { count: 0 };
}
2. static getDerivedStateFromProps(nextProps, nextState):
o Invoked before every render, both on initial mount and
updates.
o Can return an object to update the state based on props.
o Rarely used, but useful for synchronizing state with props.
Example:
render() {
return <div>{this.state.count}</div>;
}
4. componentDidMount():
o Called once the component is rendered and added to the
DOM.
o Ideal for initiating AJAX calls, subscribing to services, or
manipulating the DOM.
componentDidMount() {
console.log('Component mounted!');
}
Updating :-
When the component is re-rendered due to state or props
changes
2. shouldComponentUpdate(nextProps, nextState):
o Called before re-rendering the component.
o Returns a boolean indicating whether the component
should update.
o Useful for performance optimization e.g., preventing
unnecessary renders.
shouldComponentUpdate(nextProps, nextState) {
return nextState.count !== this.state.count;
}
3. render():
o Already mentioned above; called during each render cycle.
4. getSnapshotBeforeUpdate(prevProps, prevState):
o Called right before changes from the virtual DOM are
applied to the actual DOM.
o Can capture information e.g., scroll position before the
update.
o The return value of this method will be passed to
componentDidUpdate().
getSnapshotBeforeUpdate(prevProps, prevState) {
// Capture scroll position
return prevState.scrollPosition;
}
5. componentDidUpdate(prevProps, prevState, snapshot):
o Called after the component updates and the changes are
reflected in the DOM.
o Useful for side-effects like fetching data or manipulating
the DOM after an update.
o Receives the previous props, state, and (if returned) the
snapshot from getSnapshotBeforeUpdate.
1. componentWillUnmount():
o Called right before the component is removed from the
DOM.
o Useful for cleanup, like canceling network requests,
clearing timers, or unsubscribing from services.
componentWillUnmount() {
console.log('Component will unmount!');
}
Error Handling :-
When an error is thrown during rendering.
1. static getDerivedStateFromError(error):
o Called when an error is thrown during rendering or lifecycle
methods.
o Allows you to update state to indicate an error occurred
and render a fallback UI.
static getDerivedStateFromError(error) {
return { hasError: true };
}
2. componentDidCatch(error, info):
o Called after an error is caught in a lifecycle method or
render.
o Allows for logging error information and further error
handling.
componentDidCatch(error, info) {
console.log('Error:', error);
console.log('Error Info:', info);
}