Introduction

Almost everyone uses useEffect in React for fetching data, timers, or adding event listeners. The part that causes the most silent bugs is the cleanup function. Skip it or write it incorrectly and you get memory leaks, duplicate handlers firing, or the infamous setState on unmounted component. This post shows, with concrete examples, how to write a correct cleanup every time.

What useEffect does and what cleanup means

useEffect is for side effects — work that isn’t directly part of rendering. Its shape:

useEffect(() => {