React  

When Should I Use useEffect in React?

In React, useEffect is the go-to hook for managing side effects—actions that happen outside the normal component rendering flow.

If you're fetching data, setting up a subscription, manually changing the DOM, or working with timers, you’re in useEffect territory.

✅ What is useEffect Used For?

React's rendering is pure, but sometimes you need to:

  • Fetch data from an API
  • Set up a setInterval or setTimeout
  • Attach or clean up event listeners
  • Sync component state with localStorage or the URL

useEffect lets you run code after the DOM is updated.

🧠 Example

useEffect(() => {
    console.log("Component mounted!");
    return () => console.log("Component will unmount!");
}, []);

Explanation

  • The [] dependency array means it runs only once (like componentDidMount in class components).
  • The returned function is the cleanup function, like componentWillUnmount.

🔄 When Does useEffect Run?

Dependency Array Behavior
[] Run once on mount
[someVar] Run on the mount, and when someVar changes
(no array) Run after every render

🚫 Common Mistakes with useEffect

  • Forgetting the dependency array → causes infinite loops
  • Incorrect dependencies → can cause stale data or unnecessary re-renders
  • Updating state inside useEffect without guard conditions → can cause render loops

🛠️ Pro Tip

Use the React DevTools to debug hooks and watch when your effects fire. You can also create custom hooks (e.g. useFetch) to abstract effect logic.