React Hooks

A Quick Guide to the useEffect Hook in React

5 min read

  • September 28,2024
  • Yash Garg

The useEffect hook in React is essential for handling side effects in functional components, such as data fetching, DOM updates, or subscriptions. It replaces lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount used in class components.

Basic Syntax

useEffect takes two arguments:

  1. A function:Contains the side effect logic.
  2. An optional dependency array:Controls when the effect runs.

The effect runs on initial render and when dependencies change. If no dependency array is provided, it runs after every render.

Example: Data Fetching

Cleanup with useEffect

You can return a cleanup function to clear side effects, like timers or subscriptions, before the component unmounts.

Effects with Dependencies

You can trigger effects based on state or prop changes by listing them in the dependency array.

Best Practices

  • Clean up side effects to avoid memory leaks.
  • Limit unnecessary re-renders by carefully managing the dependency array.
  • Use multiple effects if needed to keep logic clear.

The useEffect hook simplifies handling side effects in functional components, making it easier to manage data fetching, DOM manipulation, and more.