🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Class Lifecycle to Hooks: A Migration Map

React FundamentalsLifecycleđŸŸĸ Free Lesson

What You'll Learn

  • 1Name the three lifecycle phases and locate each in a function component
  • 2Translate class lifecycle methods into effects with correct dependencies
  • 3Recognise the methods that have no hook equivalent and choose a replacement
  • 4Migrate a component incrementally without breaking its behaviour

The three phases React gives you

Every class component passes through mounting, when it is inserted into the tree; updating, when props or state change and React recomputes the output; and unmounting, when it is removed. The class API exposes each phase through a set of methods, and the hooks API exposes the same moments through a smaller, more composable set of primitives.

The mapping is worth internalising because a large fraction of legacy React code is written in classes, and reading it fluently makes migrations mechanical rather than mysterious. It is also worth internalising because the hooks versions behave differently in two ways that matter: effects run after the browser has painted unless you reach for the layout variant, and effects re-run whenever their dependencies change rather than only when a particular field changes.

  • mounting corresponds to the lazy initializer of useState, the first run of an effect, and the layout effect when the DOM must be measured immediately
  • updating corresponds to an effect re-running because one of its dependencies changed
  • unmounting corresponds to the cleanup function that the effect returned
  • error handling still lives in the class lifecycle, which is why error boundaries remain classes
  • render output corresponds to the body of the function component itself

Mount: where initialisation belongs

The constructor and getInitialState collapse into the lazy initialiser of useState, which is the right place for expensive setup that must happen once.

Class methodHook equivalentNotes
constructor with propsuseState with a function initializerThe initializer runs once, so costly work belongs there
static getDerivedStateFromProps on mountCompute during renderPrefer deriving rather than storing a copy
componentDidMountuseEffect with an empty dependency arrayRuns after paint, not synchronously
componentDidMount with a subscriptionuseEffect returning a cleanupThe cleanup is the unmount path
renderThe component function bodyKeep it pure

A common mistake is doing expensive work in the constructor and then also fetching in componentDidMount. In the hooks world, keep the cheap, synchronous initialisation in the state initializer and let effects handle anything that talks to the network, the DOM, or a third-party library.

Update: what componentDidUpdate became

In a class, componentDidUpdate receives the previous props and state, which makes it easy to compare and react. Hooks remove that argument, so the comparison becomes a dependency array: list the values you read, and React decides when to re-run.

function MessageThread({ threadId, messages }) {
  const scrollRef = useRef(null);
  const previousCount = useRef(0);

  useEffect(() => {
    const el = scrollRef.current;
    if (el) el.scrollTop = el.scrollHeight;
  }, [threadId, messages]);

  useEffect(() => {
    if (messages.length > previousCount.current) {
      previousCount.current = messages.length;
    }
  }, [messages]);

  return (
    <div ref={scrollRef} className="thread">
      {messages.map((m) => (
        <p key={m.id}>{m.body}</p>
      ))}
    </div>
  );
}

The scroll effect re-runs when the thread changes or the message list is replaced, which is the equivalent of checking for both conditions inside componentDidUpdate. The second effect tracks the previous count in a ref, which is how you reproduce the compare-with-previous-props pattern when you genuinely need it.

Unmount, and the cleanup contract

The componentWillUnmount method has a direct counterpart: the function you return from an effect. The difference is that cleanup also runs before every re-run, so the code you write must be correct for both cases. That is why you remove the listener rather than only on unmount, and why you abort the request rather than merely setting a flag.

function useInterval(callback, delay) {
  const saved = useRef(callback);

  useEffect(() => {
    saved.current = callback;
  });

  useEffect(() => {
    if (delay === null) return undefined;
    const id = setInterval(() => saved.current(), delay);
    return () => clearInterval(id);
  }, [delay]);
}

This hook is the migration of a class that stored a timer handle in the instance and cleared it in two places. Keeping the latest callback in a ref means the interval is created once per delay change while still calling the current function, which is exactly the behaviour a class achieved by reading this.props inside the tick.

The methods with no clean equivalent

Three class features do not translate one to one, and knowing the replacements in advance prevents awkward workarounds.

getDerivedStateFromProps is best replaced by deriving during render: compute the value you would have stored, and store nothing. When the derived value must be preserved across updates, a state-during-render adjustment or a key on the component is usually clearer. shouldComponentUpdate and PureComponent map to React.memo for function components, with the same caveat about referential equality.

getSnapshotBeforeUpdate, which reads the DOM between render and commit, has no hook. The practical replacements are a callback ref with a ResizeObserver or IntersectionObserver, a library that manages scroll anchoring, or, rarely, a small class component used purely for that one feature. componentDidMount and componentDidUpdate are not a pair you should try to unify in hooks; one effect with the right dependencies covers both.

A migration, end to end

Consider a component that subscribes to a status feed, tracks the previous message count to decide whether to notify, and cleans up on unmount. In a class, that logic spreads across three methods and an instance field. In hooks, it collapses into one effect plus one ref, and the behaviour stays identical.

function useStatusFeed(roomId, onAlert) {
  const [status, setStatus] = useState('connecting');
  const seen = useRef(0);

  useEffect(() => {
    const feed = openFeed(roomId);
    setStatus('connecting');

    feed.onStatus(() => setStatus('live'));
    feed.onMessage((message) => {
      if (message.severity === 'alert' && message.id > seen.current) {
        seen.current = message.id;
        onAlert(message);
      }
    });

    return () => feed.close();
  }, [roomId, onAlert]);

  return status;
}

The class version needed a constructor to bind handlers, componentDidMount to open the feed, componentDidUpdate to reopen when the room changed, and componentWillUnmount to close it. The hook version states the same facts in one place: open when the room changes, close when it changes again or the component goes away. The ref carries the previous value, which is the only piece of state that never needed to trigger a render.

Migrating incrementally

You do not need a big bang. A class component can call a hook as long as it extends React.Component and the hook lives in a function component it renders, so the common strategy is to extract the risky logic first and leave the shell in place. Move subscriptions into a custom hook, then state into a second, then finally convert the shell once the logic is already tested.

Keep the behaviour locked down with tests before you start, especially around scroll position, focus, and timers, because those are the properties that change silently when the timing of setup shifts from a synchronous constructor to a post-paint effect. Convert, run the tests, then remove the class. When the component turns out to be mostly markup with one subscription, the migration usually leaves it shorter by a third; when it turns out to be a state machine spread across lifecycle methods, the migration is really a redesign, and that is worth recognising before you start rather than halfway through.

Common Mistakes

Porting componentDidMount logic into a layout effect by habit and blocking paint

Fix: Default to useEffect and switch to the layout variant only when you must measure or mutate the DOM before paint

Storing a derived value in state that was previously computed in getDerivedStateFromProps

Fix: Compute it during render instead, and keep only genuinely independent values in state

Writing cleanup that only runs on unmount and forgetting the before-rerun case

Fix: Make the cleanup correct for both, which is what aborting and disconnecting already achieve

Converting an entire class in one commit with no intermediate tests

Fix: Extract hooks first, test them, then convert the shell

Best Practices

  • Read a class as a sequence: initializer, effects, cleanup, then decide which hook each becomes
  • Prefer one effect with a correct dependency array over several effects that must stay in sync
  • Reach for the layout effect only when measuring or mutating the DOM before paint is required
  • Keep a ref for previous values when you genuinely need a compare-with-previous pattern
  • Lock down scroll, focus, and timer behaviour with tests before migrating

Key Takeaways

  • Mount, update, and unmount map to initializers, dependency-driven effects, and cleanup functions
  • The dependency array replaces the previous-props comparison of componentDidUpdate
  • Cleanup runs before every re-run as well as on unmount, so it must cancel rather than patch
  • getSnapshotBeforeUpdate and the derived-state methods have no direct hook and need alternatives
  • Migrate by extracting tested hooks first, then converting the class shell
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert React Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement