What is useEffect and how do you use it for side effects?

· Category: React

Short answer

useEffect lets you perform side effects in functional components. It runs after render and can be scoped to specific dependencies or cleanup logic.

How it works

useEffect accepts a function and an optional dependency array. React runs the effect after committing changes to the screen. If you return a function from the effect, React runs it before re-running the effect or unmounting the component.

Example

import { useState, useEffect } from 'react';

function UserList() {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    let cancelled = false;

    fetch('/api/users')
      .then((res) => res.json())
      .then((data) => {
        if (!cancelled) setUsers(data);
      });

    return () => {
      cancelled = true; // cleanup to avoid setting state on unmounted component
    };
  }, []);

  return (
    <ul>
      {users.map((u) => <li key={u.id}>{u.name}</li>)}
    </ul>
  );
}

Tips

  • Do not forget the dependency array; omitting it causes the effect to run after every render.
  • Use a linter rule for exhaustive dependencies to catch missing values.
  • Split unrelated logic into separate useEffect calls for clarity.