Logo
HTMLCSSJavaScriptReactjsnewContactUpdates

Get started today

HTMLCSSJavaScriptReactjsnewContactUpdates

Tools

Resume BuilderQR GeneratorVS Code Editor

Connect

GitHubWhatsApp Channel
Class Components
import and export

React Component Lifecycle

By Saket Bhatnagar•April 27, 2025•Beginner to Intermediate

Table of Contents

  1. React Component Lifecycle

React Component Lifecycle

  1. 1React Component Lifecycle refers to the different stages a component goes through during its existence — from being added to the UI (DOM), updated, and finally removed from the UI
  2. 2There are 3 main phases in the lifecycle: Mounting, Updating, and Unmounting
  3. 3 Mounting Phase: The component is created and added to the UI.
    • constructor(props) – called first, used to set initial state and bind methods.
    • getDerivedStateFromProps(props, state) – rarely used, allows updating state based on props before rendering (static method).
    • render() – required, returns the JSX UI.
    • componentDidMount() – runs after the component is inserted into the DOM, good for API calls, timers.
  4. 4Updating Phase: The component updates when state or props change.
    • getDerivedStateFromProps(props, state) – runs before every render, rarely used.
    • shouldComponentUpdate(nextProps, nextState) – decides if the component should re-render (returns true/false).
    • render() – updates the UI with new props or state.
    • getSnapshotBeforeUpdate(prevProps, prevState) – captures some information (like scroll position) before the update is applied.
    • componentDidUpdate(prevProps, prevState, snapshot) – runs after the update, good for reacting to state/prop changes.
  5. 5Unmounting Phase: The component is removed from the DOM.
    • componentWillUnmount() – used for cleanup: clear timers, cancel API calls, remove event listeners.
  6. 6All Lifecycle Methods with Arguments:
    • constructor(props) – initialize state, bind methods.
    • getDerivedStateFromProps(props, state) – sync state with props (rarely needed), static method.
    • render() – return UI JSX, no arguments.
    • componentDidMount() – no arguments, side effects after first render.
    • shouldComponentUpdate(nextProps, nextState) – control re-rendering for performance (returns true/false).
    • getSnapshotBeforeUpdate(prevProps, prevState) – capture values before DOM updates (returns snapshot value).
    • componentDidUpdate(prevProps, prevState, snapshot) – respond to updates after render.
    • componentWillUnmount() – no arguments, cleanup before component is destroyed.
  7. 7Interview Key Points: Sequence of lifecycle methods get called
    • Mounting: constructor(props) → getDerivedStateFromProps(props, state) → render() → componentDidMount()
    • Updating: getDerivedStateFromProps(props, state) → shouldComponentUpdate(nextProps, nextState) → render() → getSnapshotBeforeUpdate(prevProps, prevState) → componentDidUpdate(prevProps, prevState, snapshot)
    • Unmounting: componentWillUnmount()
  8. 8In modern React, functional components use the useEffect Hook to handle similar logic as these lifecycle methods
  9. 9Common Interview Doubts:
    • Use componentDidMount() for API calls after the first render.
    • Use componentDidUpdate() when props or state change and you need to react.
    • Use componentWillUnmount() to clear intervals, timeouts, or cancel network requests.
    • shouldComponentUpdate() is used to prevent unnecessary re-renders.
    • Prefer function components + useEffect for new projects.
  10. 10Easy Way to Remember:
    Mounting = Component is added,
    Updating = Component changes,
    Unmounting = Component is removed
  11. 11Let's imagine a class component that tracks someone's relationship status. We'll use lifecycle methods to simulate how things change over time!
  12. 12

    Example: Class Component with Lifecycle (Relationship Theme)

    1class RelationshipStatus extends React.Component {
    2 constructor(props) {
    3 super(props);
    4 this.state = { status: 'Single 😎' };
    5 console.log('constructor: Just born, no feelings yet.');
    6 }
    7
    8 componentDidMount() {
    9 console.log('componentDidMount: Met someone special ❤️');
    10 setTimeout(() => {
    11 this.setState({ status: 'In a Relationship 💑' });
    12 }, 2000); // After 2 seconds, relationship starts
    13 }
    14
    15 componentDidUpdate(prevProps, prevState) {
    16 if (prevState.status !== this.state.status) {
    17 console.log('componentDidUpdate: Status changed to', this.state.status);
    18 }
    19 }
    20
    21 componentWillUnmount() {
    22 console.log('componentWillUnmount: Breakup 💔, moving on...');
    23 }
    24
    25 render() {
    26 return (
    27 <div>
    28 <h1>Current Status: {this.state.status}</h1>
    29 <button onClick={() => this.setState({ status: 'It's Complicated 🤔' })}>
    30 Change Mood
    31 </button>
    32 </div>
    33 );
    34 }
    35}
    💡

    Note

    Explanation:
    • constructor: Initial phase, no feelings yet, just born.
    • componentDidMount: They meet and after a short while, get into a relationship.
    • componentDidUpdate: Every time their relationship status changes (mood swings!), this logs the change.
    • componentWillUnmount: When the component is removed (they leave React app or the page), the breakup happens, and they move on.

Share this article

Last updated: April 27, 2025

Join Our Community

Login to Join

© 2025 Saket Bhatnagar. All rights reserved.

    ☕