Skip to content
intermediatePhase 36 · React

React Lifecycle

Understand mounting, updating, and unmounting phases in functional components.

30m
0 problems
Topic Progress0%

Mounting Phase

Mounting Phase

The mounting phase happens when a component is first rendered to the DOM.

Functional Components

function UserProfile({ userId }) {
  const [user, setUser] = useState(null);

  // Runs after first render (like componentDidMount)
  useEffect(() => {
    console.log("Component mounted");
    fetchUser(userId).then(setUser);

    // Cleanup (like componentWillUnmount)
    return () => {
      console.log("Component will unmount");
    };
  }, []); // Empty array = runs once on mount

  // Runs after every render (no dependency array)
  useEffect(() => {
    console.log("Component rendered");
  });

  if (!user) return <div>Loading...</div>;

  return <div>{user.name}</div>;
}

What Happens on Mount

  1. Component function is called
  2. JSX is rendered to Virtual DOM
  3. Virtual DOM is committed to real DOM
  4. Effects run (useEffect with [])

Common Mount Tasks

  • Fetch initial data
  • Set up subscriptions
  • Add event listeners
  • Initialize third-party libraries
function Map({ center }) {
  const mapRef = useRef(null);

  useEffect(() => {
    // Initialize map on mount
    const map = new google.maps.Map(mapRef.current, {
      center,
      zoom: 12
    });

    // Cleanup on unmount
    return () => {
      map.destroy();
    };
  }, []);

  return <div ref={mapRef} style={{ height: "400px" }} />;
}

Updating Phase

Updating Phase

The updating phase happens when props or state change.

Functional Components

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

  // Runs after every render when dependencies change
  useEffect(() => {
    document.title = `Count: ${count}`;
  }, [count]); // Re-runs when count changes

  // Runs when initialCount changes
  useEffect(() => {
    setCount(initialCount);
  }, [initialCount]);

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

What Triggers Updates

  1. State changes (useState, useReducer)
  2. Prop changes
  3. Parent re-renders
  4. Context changes

Update Flow

  1. New props/state received
  2. Component re-renders
  3. Virtual DOM is diffed
  4. Only changed parts are updated in real DOM
  5. Effects run if dependencies changed

Conditional Effects

function DataComponent({ id, type }) {
  const [data, setData] = useState(null);

  // Only runs when id changes
  useEffect(() => {
    fetchData(id).then(setData);
  }, [id]);

  // Only runs when type changes
  useEffect(() => {
    logTypeChange(type);
  }, [type]);

  return <div>{data ? JSON.stringify(data) : "Loading..."}</div>;
}

Unmounting Phase

Unmounting Phase

The unmounting phase happens when a component is removed from the DOM.

Functional Components

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

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

    // Cleanup runs on unmount
    return () => {
      clearInterval(interval);
      console.log("Timer cleaned up");
    };
  }, []);

  return <p>Count: {count}</p>;
}

What Happens on Unmount

  1. Component is removed from DOM
  2. Cleanup functions run
  3. Effects are cleaned up

Common Cleanup Tasks

  • Clear timers/intervals
  • Cancel API requests
  • Remove event listeners
  • Close WebSocket connections
  • Unsubscribe from subscriptions

Cleanup Pattern

function useSubscription(topic) {
  useEffect(() => {
    const unsubscribe = subscribe(topic);

    return () => {
      unsubscribe();
    };
  }, [topic]);
}

// Cleanup before next effect
function Component({ userId }) {
  useEffect(() => {
    const controller = new AbortController();

    fetch(`/api/users/${userId}`, { signal: controller.signal });

    // Runs when userId changes AND on unmount
    return () => controller.abort();
  }, [userId]);
}

Conditional Rendering

function App() {
  const [show, setShow] = useState(true);

  return (
    <div>
      <button onClick={() => setShow(!show)}>Toggle</button>
      {show && <Timer />}
    </div>
  );
}

// Timer mounts/unmounts as show toggles
// Cleanup runs each time Timer unmounts

Practice Problems

0/3solved
Build React Lifecycle Component

Create a reusable React component implementing React Lifecycle. Include proper state management and accessibility.

Solution
// Production-ready component with:
// - Proper TypeScript types
// - Accessibility (ARIA)
// - Error boundaries
// - Loading states
// - Memoization where needed
React Lifecycle Testing

Write unit and integration tests for React Lifecycle using React Testing Library.

Solution
// Test coverage:
// 1. Rendering tests
// 2. Interaction tests
// 3. Edge case tests
// 4. Accessibility tests
React Lifecycle Performance

Optimize React Lifecycle for performance. Consider memoization, code splitting, and bundle size.

Solution
// Optimization techniques:
// 1. React.memo / useMemo / useCallback
// 2. Code splitting with lazy()
// 3. Virtual scrolling for lists
// 4. Image lazy loading
// 5. Bundle analysis

Quiz

1. When does the mounting phase occur?

Question 1 options

2. When does cleanup run in useEffect?

Question 2 options

3. What triggers the updating phase?

Question 3 options

4. What should you do in cleanup?

Question 4 options

Flashcards

Question

When does mounting happen?

Answer

When a component is first rendered to the DOM

Question

When does cleanup run?

Answer

Before the next effect and on unmount

Question

What triggers updates?

Answer

Props or state changes

Question

What is the cleanup function?

Answer

A function returned from useEffect to clean up resources

Question

What is React Lifecycle?

Answer

React Lifecycle is a key concept in frontend development.

Revision Notes

Key Takeaways

  • 1.Mounting happens on first render
  • 2.Updates happen when props/state change
  • 3.Cleanup runs on unmount and before effects
  • 4.Empty dependency array means mount only
  • 5.Effects handle side effects

Interview Tips

  • Map lifecycle phases to useEffect patterns
  • Explain when cleanup functions run
  • Show how to handle mount, update, and unmount

Cheat Sheet

Cheat Sheet

Mounting

useEffect(() => {
  // Mount logic
  return () => {
    // Cleanup on unmount
  };
}, []);

Updating

useEffect(() => {
  // Runs when dependency changes
}, [dependency]);

Unmounting

useEffect(() => {
  const timer = setInterval(...);
  return () => clearInterval(timer); // Cleanup
}, []);

Lifecycle Phases

  1. Mounting: Component appears
  2. Updating: Props/state change
  3. Unmounting: Component removed