🔄

React Component Lifecycle Methods

Jul 4, 2024

React Component Life Cycle Methods

Introduction

  • React components have a lifecycle: birth, life, and death.
  • Lifecycle methods allow developers to insert custom logic during different phases.
  • Focus on class components for lifecycle methods.

Phases of Lifecycle

  1. Mounting Phase: Component is created and inserted into the DOM.
  2. Updating Phase: Component updates due to changes in state or props.
  3. Unmounting Phase: Component is removed from the DOM.

Mounting Phase

  • constructor: Called before the component is mounted. Used for:
    • Initializing state
    • Binding class methods
    • Must call super()
  • getDerivedStateFromProps: Called on initial mount and update.
    • Updates state based on props.
    • Rarely used, special use cases.
  • render: Responsible for returning React elements.
    • Must be pure, no state modifications.
  • componentDidMount: Called after initial render.
    • Perform API queries and other side-effects.
    • Sets the state and causes re-rendering if needed.

Updating Phase

  • getDerivedStateFromProps: Allows state updates based on changes in props.
    • Invoked on every parent component re-render.
  • shouldComponentUpdate: Determines if a re-render is necessary.
    • Can optimize performance by preventing unnecessary re-renders.
    • Consider using PureComponent for shallow comparisons.
  • render: Returns updated React elements.
  • getSnapshotBeforeUpdate: Captures properties before DOM updates.
    • Useful for operations like scrolling a chat window.
    • Example: Compute scroll position before DOM update.
  • componentDidUpdate: Called after the DOM updates.
    • Useful for operations like API queries based on prop/state changes.
    • Not invoked on initial render.

Unmounting Phase

  • componentWillUnmount: Called before component is destroyed.
    • Useful for cleanup tasks (e.g., timers, unsubscribing from data sources).

Functional Components & Lifecycle Methods

  • Hooks API provides a way to handle component side effects but with a different approach compared to lifecycle methods in class components.

Conclusion

  • Lifecycle methods enhance performance and customization in React applications.
  • Functional components can use hooks for equivalent lifecycle-like behavior.
  • Knowled Heart offers immersive learning to enhance React skills.