React Component Lifecycle Methods Complete Guide

 Last Update:2025-06-22T00:00:00     .NET School AI Teacher - SELECT ANY TEXT TO EXPLANATION.    8 mins read      Difficulty-Level: beginner

Understanding the Core Concepts of React Component Lifecycle Methods

React Component Lifecycle Methods

React components undergo several phases during their existence: Mounting, Updating, and Unmounting. Each phase includes specific lifecycle methods that provide hooks to run code when particular events occur.

Mounting Phase

This phase occurs when an instance of a component is created and inserted into the DOM. There are four primary lifecycle methods in this phase:

  1. constructor(props) -

    • Called before the component mounts.
    • Used to initialize state, bind event handlers, and set up references.
    • Does not have access to this.state or this.props.
  2. static getDerivedStateFromProps(props, state) -

    • Invoked right before rendering and anytime new props receive.
    • Should return an object containing state changes or null if no changes needed.
    • It's used when you want to update the state based on changes to props.
  3. render() -

    • Required method for class components.
    • Describes the UI that should be rendered to the DOM.
    • Note: Render should not cause side effects (like API calls).
  4. componentDidMount() -

    • Executed after the component output has been rendered to the DOM.
    • Ideal place for initial data fetching or subscriptions to APIs and services.
    • Can modify state using setState().

Updating Phase

This phase happens when there is a change in the component's props or state. The lifecycle methods during this phase include:

  1. static getDerivedStateFromProps(props, state) -

    • Also called during the updating phase.
    • Updates state based on props changes but less commonly used here since state might not reflect the most recent updates.
  2. shouldComponentUpdate(nextProps, nextState) -

    • Allows you to decide if the component should re-render or not.
    • Receives the new props and state as arguments and returns a boolean value.
    • Optimizing performance can be done using shallow comparisons in this method.
  3. render() -

    • Runs whenever there is a change in state or props.
    • Should be a pure function and free from side effects.
  4. getSnapshotBeforeUpdate(prevProps, prevState) -

    • Invoked just before the most recently rendered output is committed to the DOM.
    • Helps capture some information from the DOM (like scroll position) before it is potentially changed.
    • Returns a value or null which is accessible in componentDidUpdate.
  5. componentDidUpdate(prevProps, prevState, snapshot) -

    • Called after the component is updated in the DOM.
    • Can use prevProps and prevState to compare with current ones and then perform operations like re-fetching data or updating the DOM directly.

Unmounting Phase

Only one lifecycle method is involved in the unmounting phase:

  1. componentWillUnmount() -
    • Invoked immediately before a component is unmounted and destroyed.
    • Useful for cleaning up any resources before the component leaves the DOM (like clearing intervals, timeouts, and unsubscribing from events).
    • Should not call setState() here because the component will never re-render.

Error Handling Phase

These methods are called when there is an error during rendering, or in the lifecycle methods themselves, or in any child component:

  1. static getDerivedStateFromError(error) -

    • This method is used to render a fallback UI when an error occurs.
    • It is also used to update the state.
  2. componentDidCatch(error, info) -

    • It logs the error.
    • You can send error reports to a server.
    • It can reset the state using setState() to recover the UI in some cases.

Important Info

  • Pure Functions: React emphasizes the importance of keeping components pure functions. That means they should behave predictably, without causing side effects.

  • Avoid Side Effects in Render Method: Performing calculations or API calls inside the render method could cause unexpected behavior and lead to performance issues.

  • Optimization with shouldComponentUpdate(): Properly implemented, this method allows you to skip unnecessary rendering, leading to better performance.

  • ComponentDidMount: Use this lifecycle method for network requests, subscriptions, and similar logic that needs the component to be active in the DOM.

  • Cleanup in componentWillUnmount(): Essential to prevent memory leaks and maintain a clean application.

  • Error Boundaries using static methods: Introsuced in React 16, these classes help gracefully handle errors in the component tree, displaying a fallback UI where needed.

Here’s a simple example illustrating lifecycle methods:

Online Code run

🔔 Note: Select your programming language to check or run code at

💻 Run Code Compiler

Step-by-Step Guide: How to Implement React Component Lifecycle Methods

Mounting Phase

These methods are called when a component is being inserted into the DOM.

1. constructor(props)

The constructor is called once when the component is created. It is typically used for initializing state and binding event handlers to class instances.

import React from 'react';

class MountingComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            message: 'Hello React!'
        };
        console.log('Constructor called');
    }

    render() {
        console.log('Render method called');
        return (
            <div>
                <h1>{this.state.message}</h1>
            </div>
        );
    }

    componentDidMount() {
        console.log('ComponentDidMount called');
        this.setState({ message: 'Hello after mount!' });
    }
}

export default MountingComponent;

2. render()

The render() method is required in a class component. It examines this.props and this.state and returns a React element.

3. componentDidMount()

Called immediately after a component is mounted to the DOM. A good place to initiate network requests or set up subscriptions.

Updating Phase

These methods are called when a component is being re-rendered as a result of changes to either props or state.

4. static getDerivedStateFromProps(props, state)

It is called right before rendering the element(s) in the DOM when state or props change. This method helps in syncing state with props under certain conditions.

class UpdatingComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = { name: 'React' };
    }

    static getDerivedStateFromProps(props, state) {
        console.log('getDerivedStateFromProps called');
        return { name: props.name };
    }

    render() {
        console.log('Render method called');
        return (
            <div>
                <h1>Hello, {this.state.name}!</h1>
            </div>
        );
    }

    componentDidUpdate() {
        console.log('ComponentDidUpdate called');
    }
}

export default UpdatingComponent;

5. shouldComponentUpdate(nextProps, nextState)

Determines if the component should re-render when new props or state are received.

class ShouldComponentUpdateEx extends React.Component {
    constructor(props) {
        super(props);
        this.state = { count: 0, timestamp: Date.now() };
    }

    shouldComponentUpdate(nextProps, nextState) {
        console.log('shouldComponentUpdate called');
        return nextState.count % 2 === 0;
    }

    incrementCount = () => {
        this.setState({ count: this.state.count + 1 });
    };

    render() {
        console.log('Render method called');
        return (
            <div>
                <button onClick={this.incrementCount}>Increment</button>
                <h1>Count: {this.state.count}</h1>
            </div>
        );
    }

    componentDidUpdate(prevProps, prevState) {
        console.log('ComponentDidUpdate called');
    }
}

export default ShouldComponentUpdateEx;

This method returns a boolean value. When it returns false, the render() method does not get called.

6. render()

Similar to the render() method in the mounting phase.

7. getSnapshotBeforeUpdate(prevProps, prevState)

Called right before the changes from the virtual DOM are to be reflected in the DOM. Useful for capturing some information from the DOM before it is updated.

class SnapshotBeforeUpdateEx extends React.Component {
    constructor(props) {
        super(props);
        this.state = { count: 0, timestamp: Date.now() };
    }

    componentDidUpdate(prevProps, prevState, snapshot) {
        console.log('ComponentDidUpdate called');
        console.log('Snapshot:', snapshot);
    }

    getSnapshotBeforeUpdate(prevProps, prevState) {
        console.log('getSnapshotBeforeUpdate called');
        return { prevCount: prevState.count };
    }

    incrementCount = () => {
        this.setState({ count: this.state.count + 1 });
    };

    render() {
        console.log('Render method called');
        return (
            <div>
                <button onClick={this.incrementCount}>Increment</button>
                <h1>Count: {this.state.count}</h1>
            </div>
        );
    }
}

export default SnapshotBeforeUpdateEx;

8. componentDidUpdate(prevProps, prevState, snapshot)

Called right after the component's updates are flushed to the DOM.

Unmounting Phase

This method is called when a component is being removed from the DOM.

9. componentWillUnmount()

Called right before a component is removed from the DOM. Ideal for cleanup like invalid timers, network requests, event listeners.

class UnmountingComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = { isActive: true };
    }

    componentDidMount() {
        console.log('ComponentDidMount called');
        this.timerID = setInterval(() => {
            console.log('Timer ticked');
        }, 1000);
    }

    componentWillUnmount() {
        console.log('ComponentWillUnmount called');
        clearInterval(this.timerID);
    }

    deactivate = () => {
        this.setState({ isActive: false });
    };

    render() {
        console.log('Render method called');
        return (
            <div>
                {this.state.isActive ? (
                    <div>
                        <h1>Active!</h1>
                        <button onClick={this.deactivate}>Deactivate</button>
                    </div>
                ) : (
                    <h1>Inactive!</h1>
                )}
            </div>
        );
    }
}

export default UnmountingComponent;

Error Handling Phase

This is the latest addition to React's lifecycle methods, handling JavaScript errors anywhere in the component tree.

10. static getDerivedStateFromError(error)

Render a fallback UI after an error has been thrown.

class ErrorBoundary extends React.Component {
    constructor(props) {
        super(props);
        this.state = { hasError: false };
    }

    static getDerivedStateFromError(error) {
        // Update state so the next render will show the fallback UI.
        return { hasError: true };
    }

    componentDidCatch(error, info) {
        // Example "componentStack":
        //   in ComponentThatThrows (created by App)
        //   in ErrorBoundary (created by App)
        //   in div (created by App)
        //   in App
        logErrorToService(error, info.componentStack);
    }

    render() {
        if (this.state.hasError) {
            return <h1>Error!</h1>;
        }
        return this.props.children;
    }
}

function ComponentThatThrows() {
    throw new Error("I crashed!");
}

function App() {
    return (
        <div>
            <ErrorBoundary>
                <ComponentThatThrows />
            </ErrorBoundary>
        </div>
    );
}

export default App;

11. componentDidCatch(error, info)

Perform side effects in response to an error caught by an error boundary.

Top 10 Interview Questions & Answers on React Component Lifecycle Methods

1. What are the primary phases in a React component's lifecycle?

Answer: React components go through three primary phases:

  • Mounting Phase: When React elements are inserted into the DOM.
  • Updating Phase: When re-rendering because of a change in props or state.
  • Unmounting Phase: When a React element is being removed from the DOM.
  • In addition to these, there’s also an Error Handling Phase that deals with exceptions in the component tree.

2. List all the lifecycle methods available in class-based components.

Answer: Below are the common lifecycle methods of class-based components in React (as of React 18):

  • Mounting:

    • constructor(props)
    • static getDerivedStateFromProps(props, state)
    • render()
    • componentDidMount()
  • Updating:

    • static getDerivedStateFromProps(props, state)
    • shouldComponentUpdate(nextProps, nextState) [Deprecated in StrictMode in React 18]
    • render()
    • getSnapshotBeforeUpdate(prevProps, prevState)
    • componentDidUpdate(prevProps, prevState, snapshot)
  • Unmounting:

    • componentWillUnmount()
  • Error Handling:

    • static getDerivedStateFromError(error)
    • componentDidCatch(error, info)

3. What is the purpose of the constructor method in React?

Answer: The constructor method is used for initializing the state of a component and binding methods to the component instance. It is called before the component is mounted.

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    this.setState({ count: this.state.count + 1 });
  }

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={this.handleClick}>Increment</button>
      </div>
    );
  }
}

4. Explain getDerivedStateFromProps method and how it should be used.

Answer: getDerivedStateFromProps is a static method that returns an object to update the state based on props or null if no changes to state are needed. It is used when the state depends on incoming props.

class Welcome extends React.Component {
  static getDerivedStateFromProps(nextProps, prevState) {
    // Returns object for state updates
    return { greeting: nextProps.name };
  }

  constructor(props) {
    super(props);
    this.state = { greeting: '' };
  }

  render() {
    return (
      <div>
        <h1>Hello, {this.state.greeting}!</h1>
      </div>
    );
  }
}

5. When should componentDidMount be used?

Answer: componentDidMount is used after the component output has been rendered to the DOM. It is a great place to instantiate network requests, subscriptions, set up timers, or perform other side effects.

class Timer extends React.Component {
  constructor(props) {
    super(props);
    this.state = { time: new Date().toLocaleTimeString() };
  }

  componentDidMount() {
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );
  }

  componentWillUnmount() {
    clearInterval(this.timerID);
  }

  tick() {
    this.setState({
      time: new Date().toLocaleTimeString()
    });
  }

  render() {
    return (
      <div>
        <p>The time now is {this.state.time}.</p>
      </div>
    );
  }
}

6. What is the purpose of the componentDidUpdate method?

Answer: componentDidUpdate is invoked immediately after updating occurs. This method can’t have side effects except asynchronously in componentDidCatch or using setState. It provides access to the previous props and state.

class Counter extends React.Component {
  componentDidUpdate(prevProps, prevState) {
    if (prevState.count !== this.state.count) {
      console.log('Counter updated.');
    }
  }

  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }

  incrementCount = () => {
    this.setState(state => ({ count: state.count + 1 }));
  }

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={this.incrementCount}>Increment</button>
      </div>
    );
  }
}

7. How does getSnapshotBeforeUpdate work in React?

Answer: getSnapshotBeforeUpdate is called right before the most recently rendered output is committed to the DOM. It is used for reading the DOM before a potentially destructive update. Return a value which will be passed as a third argument to componentDidUpdate.

class ScrollingList extends React.Component {
  listRef = React.createRef();

  getSnapshotBeforeUpdate(prevProps, prevState) {
    // Are we adding new items to the list?
    // Capture the scroll position so we can adjust it after the update.
    if (prevProps.list.length < this.props.list.length) {
      const list = this.listRef.current;
      return list.scrollHeight - list.scrollTop;
    }
    return null;
  }

  componentDidUpdate(prevProps, prevState, snapshot) {
    if (snapshot !== null) {
      const list = this.listRef.current;
      list.scrollTop = list.scrollHeight - snapshot;
    }
  }

  render() {
    return (
      <ul ref={this.listRef}>
        {this.props.list.map(item => <li key={item.id}>{item.text}</li>)}
      </ul>
    );
  }
}

8. What is the significance of componentWillUnmount in React?

Answer: componentWillUnmount is used for cleanup just before a component is unmounted and destroyed. It can clear subscriptions, timers, and cancel network requests.

class WeatherFetcher extends React.Component {
  componentDidMount() {
    this.timerID = setInterval(() => this.fetchWeather(), 1000);
  }

  componentWillUnmount() {
    clearInterval(this.timerID);
  }

  fetchWeather() {
    // Fetch weather...
  }

  render() {
    return <div>Fetching Weather...</div>;
  }
}

9. Describe the static getDerivedStateFromError and componentDidCatch methods.

Answer: These two methods are used for catching errors in descendant components (similar to a JavaScript try-catch block).

  • static getDerivedStateFromError(error): It is used to update the state so that the next render shows an error message instead of the crashed component.
  • componentDidCatch(error, info): It allows you to log the error information (which includes the name of the component that crashed and where in the tree did the crash occur).
class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    // Update state so that next render displays fallback UI.
    return { hasError: true };
  }

  componentDidCatch(error, info) {
    // Log the error information
    console.log(info.componentStack);
  }

  render() {
    if (this.state.hasError) {
      // You can render any custom fallback UI
      return <h1>Oops! Something went wrong.</h1>;
    }
    return this.props.children;
  }
}

class BuggyComponent extends React.Component {
  render() {
    throw new Error('I crashed!');
  	return <h1>I am buggy</h1>;
  }
}

function App() {
  return (
    <ErrorBoundary>
      <BuggyComponent />
    </ErrorBoundary>
  );
}

10. Why were methods like componentWillReceiveProps and componentWillUpdate deprecated?

Answer: According to the official React documentation, componentWillReceiveProps and componentWillUpdate were prone to bugs and unnecessary invocations in some edge cases. These methods don't always fire as expected when dealing with async rendering which may cause stale props and states issues leading to inconsistent UIs.

To handle prop changes safely, developers are encouraged to use:

  • static getDerivedStateFromProps
  • The useEffect hook in functional components

For optimizing updates, developers can use:

  • shouldComponentUpdate
  • React.memo wrapped around functional components
  • useMemo, useCallback

These new mechanisms provide more predictable control over updates in a component’s lifecycle without the pitfalls of the old ones.

You May Like This Related .NET Topic

Login to post a comment.