Course contentsShow
← React
Lesson 318 of 2,3969. Class Components (Legacy Overview)Free lesson

From componentDidUpdate to useEffect with Deps

Translate componentDidUpdate with conditional logic to useEffect with specific dependencies that trigger updates.

From componentDidUpdate to useEffect with Deps

What You'll Learn

You'll learn how to translate componentDidUpdate logic that conditionally runs based on specific prop or state changes into a useEffect hook with a dependency array.

The Class Component Pattern

In class components, componentDidUpdate fires after every update. To avoid infinite loops or unnecessary work, you'd check which props or state actually changed:

componentDidUpdate(prevProps, prevState) {
  if (prevProps.userId !== this.props.userId) {
    // Only fetch when userId changes
    fetchUserData(this.props.userId);
  }
}

You're manually comparing old vs new values to decide whether to run your side effect.

The useEffect Translation

With useEffect, you specify which values should trigger the effect by listing them in the dependency array:

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

React automatically compares userId between renders. If it's different, your effect runs. No manual prevProps comparison needed.

Multiple Dependencies

You can track multiple values:

useEffect(() => {
  loadData(userId, filter);
}, [userId, filter]); // Runs when EITHER changes

This is equivalent to checking multiple conditions in componentDidUpdate:

if (prevProps.userId !== this.props.userId || 
    prevProps.filter !== this.props.filter) {
  loadData(this.props.userId, this.props.filter);
}

The Mental Model Shift

Stop thinking "check what changed." Start thinking "declare what matters." You're telling React: "This effect depends on these values. Re-run it when they change."

Key Takeaway: useEffect with dependencies replaces conditional componentDidUpdate logic—instead of manually comparing prevProps, you declare which values should trigger the effect, and React handles the comparison automatically.