Skip to main content
TOPIC 7 OF 8 · 2 MIN READ

Lifecycle in React and How to Control It with useEffect

In React, every component goes through a series of stages from its creation to destruction. These stages are collectively referred to as the component lifecycle. Understanding this lifecycle is crucial for managing state, performing side effects, and optimizing performance.

Key concepts

Component Lifecycle

The series of stages a component goes through from its creation to destruction: Mounting, Updating, and Unmounting.

Mounting

The component is created and inserted into the DOM. Use `useEffect` with an empty dependency array `[]` to simulate `componentDidMount`.

Updating

The component re-renders due to changes in props or state. Use `useEffect` with dependencies to handle updates.

Unmounting

The component is removed from the DOM. Use the cleanup function inside `useEffect` to simulate `componentWillUnmount`.

Step by step

The Three Phases of React Component Lifecycle:

  • Mounting: The component is created and inserted into the DOM.
  • Updating: The component re-renders due to changes in props or state.
  • Unmounting: The component is removed from the DOM.

Best Practices for Using useEffect:

  • Use Dependencies Wisely: Always include dependencies if the effect depends on them.
  • Avoid Overusing useEffect: If you can compute a value directly in the render, avoid putting it in `useEffect`.
  • Cleanup Properly: Use the cleanup function for resource management.
  • Memoize Callbacks: Use `useCallback` or `useMemo` to prevent unnecessary re-renders.

Examples

Mimicking componentDidMount:

import React, { useEffect, useState } from 'react';

function App() {
  const [data, setData] = useState(null);

  useEffect(() => {
    // Fetch data when component mounts
    fetch('https://api.example.com/data')
      .then((response) => response.json())
      .then((data) => setData(data));
  }, []); // Empty dependency array ensures it runs only once

  return <div>{data ? `Data: ${data}` : 'Loading...'}</div>;
}

Mimicking componentDidUpdate:

import React, { useEffect, useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    console.log(`Count has been updated to: ${count}`);
  }, [count]); // Runs only when `count` changes

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

Mimicking componentWillUnmount:

import React, { useEffect, useState } from 'react';

function Timer() {
  const [time, setTime] = useState(0);

  useEffect(() => {
    const interval = setInterval(() => setTime((prev) => prev + 1), 1000);

    return () => {
      clearInterval(interval); // Cleanup on unmount
    };
  }, []); // Empty array ensures interval is set only once

  return <div>Time: {time}s</div>;
}

Cleanup a Subscription:

useEffect(() => {
  const handleResize = () => console.log('Window resized');
  window.addEventListener('resize', handleResize);

  return () => {
    window.removeEventListener('resize', handleResize); // Cleanup on unmount
  };
}, []); // Runs once on mount, cleans up on unmount

Stuck on this one? Talk to Sumit.

Keys: F focus mode · ← → previous / next topic · Esc leave focus