What is the React component lifecycle in functional components?

· Category: React

Short answer

In functional components, useEffect replaces lifecycle methods. You control when it runs by providing a dependency array.

How it works

  • Mount: Run code after the component appears on screen with an empty dependency array [].
  • Update: Run when specific dependencies change by including them in the array.
  • Unmount: Return a cleanup function from useEffect; React calls it before the component is removed.

Example

import { useEffect } from 'react';

function ChatRoom({ roomId }) {
  useEffect(() => {
    const connection = createConnection(roomId);
    connection.connect();

    return () => {
      connection.disconnect(); // cleanup on unmount or roomId change
    };
  }, [roomId]);

  return <div>Room: {roomId}</div>;
}

Why it matters

Understanding useEffect dependencies prevents stale closures and infinite loops. The React team recommends thinking in terms of synchronization rather than a rigid lifecycle.