Labs ICT
โญ Pro Login

useEffect Hook

Handling side effects in your components.

What is useEffect?

The useEffect Hook is your go-to tool for handling side effects in function components. Side effects are things that happen outside of the component's rendering process - like fetching data from an API, updating the document title, setting up subscriptions, or manually changing the DOM. Without useEffect, function components were stuck being pure and static.

Think of useEffect as a Swiss Army knife for your component's lifecycle. It replaces componentDidMount, componentDidUpdate, and componentWillUnmount all in one API. You can run code after every render, only when certain values change, or set up and clean up resources. It's incredibly flexible once you get the hang of it.

The Dependency Array

The second argument to useEffect is the dependency array. This is where you tell React which values the effect depends on. When any value in the array changes, the effect re-runs. If you pass an empty array, the effect only runs once on mount. If you omit the array entirely, the effect runs after every single render - which is usually not what you want.

function SearchResults({ query }) {
  const [results, setResults] = useState([])
  useEffect(() => {
    fetch(`/api/search?q=${query}`)
      .then(res => res.json())
      .then(data => setResults(data))
  }, [query])
  return results.map(r => <p key={r.id}>{r.title}</p>)
}
Try it Yourself โ†’

Cleanup Functions

Some effects need to clean up after themselves. Think of subscriptions, timers, or event listeners - if you don't remove them when the component unmounts, you'll have memory leaks everywhere. useEffect lets you return a cleanup function that React runs before the effect re-runs or when the component unmounts.

function Timer() {
  const [seconds, setSeconds] = useState(0)
  useEffect(() => {
    const interval = setInterval(() => {
      setSeconds(s => s + 1)
    }, 1000)
    return () => clearInterval(interval)
  }, [])
  return <p>{seconds} seconds elapsed</p>
}
Try it Yourself โ†’

Common Use Cases

The most common use case for useEffect is data fetching. When a component mounts or a dependency changes, you fetch fresh data and update state with the response. You'll also use it for syncing with external systems, like browser APIs or third-party libraries. Just remember to always include the right dependencies in your array.

A common mistake is forgetting dependencies or including too many. ESLint's react-hooks/exhaustive-deps rule will help you catch these issues. If your effect is doing too many things, consider splitting it into multiple useEffect calls with different dependencies. Each effect should have one clear responsibility.

๐Ÿงช Quick Quiz

What does useEffect do?