Back to Curriculum

Side Effects and Hooks (useEffect)

📚 Lesson 5 of 18 ⏱️ 50 min

Side Effects and Hooks (useEffect)

50 min

The Effect Hook, `useEffect`, lets you perform side effects in function components.

Data fetching, setting up a subscription, and manually changing the DOM in React components are all examples of side effects.

`useEffect` runs after every render, including the first one. You can also specify a dependency array to control when it runs.

The dependency array determines when the effect re-runs. An empty array [] means the effect runs only once after the initial render, while omitting it means the effect runs after every render.

Cleanup functions returned from useEffect are essential for preventing memory leaks. They run when the component unmounts or before the effect runs again.

Multiple useEffect hooks can be used in a single component, each handling different side effects, making code more organized and easier to understand.

Key Concepts

  • useEffect handles side effects in functional components.
  • Dependency array controls when effects re-run.
  • Cleanup functions prevent memory leaks from subscriptions and timers.
  • Effects run after the DOM has been updated.
  • Multiple effects can be used to separate concerns.

Learning Objectives

Master

  • Using useEffect for side effects like data fetching
  • Understanding dependency arrays and their impact
  • Implementing cleanup functions for subscriptions and timers
  • Organizing multiple effects in a component

Develop

  • Understanding React's lifecycle in functional components
  • Recognizing when side effects are needed
  • Preventing common memory leak patterns

Tips

  • Always include dependencies in the dependency array to avoid stale closures.
  • Use cleanup functions for subscriptions, timers, and event listeners.
  • Separate unrelated side effects into multiple useEffect hooks.
  • Use ESLint plugin to catch missing dependencies automatically.

Common Pitfalls

  • Forgetting to include dependencies in the dependency array, causing stale closures.
  • Not cleaning up subscriptions or timers, leading to memory leaks.
  • Including unnecessary dependencies that cause excessive re-renders.
  • Using useEffect for state updates that should use useState or useReducer.

Summary

  • useEffect handles side effects after component renders.
  • Dependency arrays control when effects re-execute.
  • Cleanup functions are essential for preventing memory leaks.
  • Multiple effects help organize and separate concerns.

Exercise

Use `useEffect` to change the document title based on the component's state.

import { useState, useEffect } from 'react';

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

  useEffect(() => {
    document.title = `You clicked ${count} times`;
  });

  return (
    <button onClick={() => setCount(count + 1)}>
      Update Title
    </button>
  );
}

Exercise Tips

  • Add [count] to dependency array to fix the ESLint warning.
  • Consider adding a cleanup function to reset the title on unmount.
  • Try adding multiple effects for different side effects.
  • Test the effect with React DevTools Profiler.

Code Editor

Output