Post cover
June 25, 2025

Reacts useEffect hook is one of the most powerful and commonly misunderstood tools. Whether you’re fetching data, adding event listeners, or syncing state, useEffect makes it possible.

React’s useEffect hook is one of the most powerful and commonly misunderstood tools. Whether you’re fetching data, adding event listeners, or syncing state, useEffect makes it possible.
In this post, we’ll dive deep into:
  • What is useEffect?
  • When to use it?
  • How it works in React & Next.js
  • Common patterns and pitfalls
  • Real-world examples

What is useEffect?

useEffect is a React Hook that lets you run side effects in function components. Side effects include:
  • Fetching data
  • Changing the DOM
  • Subscribing to events
  • Setting up timers

When Should You Use useEffect?

Use it when:
  • You need to fetch data when the component mounts.
  • You want to run code after a render (e.g., animation triggers).
  • You need to listen to window or DOM events.
  • You want to sync external systems or APIs with React state.
 

Basic Syntax

 

Common Use Cases with Examples

  1. Fetch Data on Component Mount
  1. Add Event Listener (e.g., Window Resize)
  1. Set a Timer
  1. Using useEffect in Next.js
    1. Next.js is just React under the hood. useEffect works the same way, but you must not use it for SSR logic — it runs only on the client.
      Example: Logging page views
      ✅ Tip: Use getServerSideProps or getStaticProps for server-side data fetching, and useEffect for client-side actions.

Common Mistakes

  1. Forgetting the Dependency Array
    1. ✅ Fix:
  1. Updating state without checking dependencies
    1. This creates an infinite loop!
      ✅ Fix: use a callback or conditional logic
       

When Not to Use useEffect

Avoid using useEffect:
  • For logic that can be derived purely from props or state.
  • For synchronous updates inside render logic.
  • If you're trying to use it just to trigger re-renders.
 

Pro Tips

  • Always clean up subscriptions and timers to avoid memory leaks.
  • Use AbortController for fetch cancellation.
  • Break large effects into smaller specific useEffect calls.
 

Summary

Use case
When to use useEffect?
Fetch API data
On component mount or param change
Set interval or timeout
On mount, and clean up on unmount
DOM manipulation
For client-side interactions only
Event listeners
Add on mount, remove on unmount
Syncing props/state
Carefully with dependency array

Final Words

React's useEffect is a swiss-army knife — powerful but easy to misuse. Understand when and why you’re using it. When used correctly, it allows you to build dynamic, performant, and reactive applications.
Next time you add an API call or scroll listener, remember: "Does this belong in a useEffect?"