DEV Community

Cover image for USE EFFECT HOOK
Srashti Gupta
Srashti Gupta

Posted on

USE EFFECT HOOK

Here’s a clean, well-structured, and engaging blog post draft about the React useEffect hook, including best practices, examples, and common pitfalls, all based on the latest guidance and real-world scenarios:


Demystifying the useEffect Hook in React

Why I Wrote This Post

When I first started building React apps, I found myself confused about when and how to use the useEffect hook. It’s a powerful tool for handling side effects, but it can also introduce subtle bugs if not used carefully. In this post, I’ll share what I’ve learned about useEffect, show you practical examples, and help you avoid common mistakes—so you can write more predictable and efficient React code.



What Is useEffect?

The useEffect hook lets you perform side effects in your React functional components. Side effects include tasks like:

  • Fetching data from an API
  • Setting up event listeners
  • Updating the DOM directly
  • Managing timers or subscriptions[1][3][4][17]

Before hooks, these tasks were handled in class components using lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount. With useEffect, you can do all of this in functional components—making your code more concise and easier to manage[1][3][17].


Basic Syntax

useEffect(() => { // Side effect logic here return () => { // Optional cleanup logic here }; }, [dependencies]); 
Enter fullscreen mode Exit fullscreen mode
  • Effect function: Runs after every render by default.
  • Cleanup function (optional): Runs before the effect is re-executed or when the component unmounts—useful for cleaning up subscriptions, timers, or event listeners.
  • Dependencies array: Controls when the effect runs. If empty ([]), the effect runs only once after the initial render; if omitted, it runs after every render; if you list variables, it runs when any of those variables change[3][4][8][13][15].

Practical Examples

1. Run Once on Mount

useEffect(() => { console.log("Component mounted!"); }, []); // Only runs once after the first render 
Enter fullscreen mode Exit fullscreen mode

2. Run When a Value Changes

const [count, setCount] = useState(0); useEffect(() => { document.title = `Count: ${count}`; }, [count]); // Runs every time count changes 
Enter fullscreen mode Exit fullscreen mode

3. Fetch Data on Mount

useEffect(() => { async function fetchData() { const response = await fetch('https://api.example.com/data'); const data = await response.json(); setData(data); } fetchData(); }, []); // Runs only once after the first render 
Enter fullscreen mode Exit fullscreen mode

4. Cleanup Example (Event Listener)

useEffect(() => { function handleResize() { console.log('Window resized!'); } window.addEventListener('resize', handleResize); return () => window.removeEventListener('resize', handleResize); }, []); // Adds and cleans up the event listener 
Enter fullscreen mode Exit fullscreen mode

Best Practices

  • Always specify the dependencies array: This prevents unnecessary or missed effect executions and avoids performance issues[8][16].
  • Include all dependencies: List every variable from the component scope that your effect uses. Missing dependencies can cause bugs or stale data[8][16].
  • Use multiple useEffect hooks for separate concerns: This keeps your code organized and easier to debug[2][8].
  • Always clean up side effects: Return a cleanup function to remove event listeners, timers, or subscriptions to prevent memory leaks[8][15].
  • Avoid overusing useEffect: Not all logic needs to be inside useEffect. For derived state or simple computations, use regular variables or memoization[2][6][8].

Common Pitfalls and How to Avoid Them

Pitfall How to Avoid It
Forgetting dependencies Always include all variables your effect uses in the dependency array[8][16].
Infinite loops from state updates Don’t update state unconditionally inside useEffect; use guards or conditions if needed[8][16].
Memory leaks from uncleaned side effects Always return a cleanup function to remove listeners, timers, or subscriptions[8][15].
Overcomplicating effects Only use useEffect for true side effects, not for simple value calculations or rendering logic[8][2].
Using useEffect for data transformation Compute derived data directly in render, not in useEffect[2][8].

Summary

The useEffect hook is essential for handling side effects in React functional components. By understanding its syntax, using the dependency array correctly, and following best practices, you can avoid common bugs and write more maintainable code. Remember to clean up after your effects, and don’t use useEffect for tasks that can be handled directly in render.


Let’s Discuss!

  • Have you run into tricky bugs with useEffect?
  • Do you have tips or patterns that work well for you?
  • Any questions about dependencies or cleanup?

Drop your experiences and questions in the comments below!

[1] https://www.geeksforgeeks.org/reactjs-useeffect-hook/
[2] https://www.zipy.ai/blog/useeffect-hook-guide
[3] https://namastedev.com/blog/react-useeffect-hook-deep-dive-7/
[4] https://www.w3schools.com/react/react_useeffect.asp
[5] https://deadsimplechat.com/blog/react-useeffect-a-complete-guide-with-examples/
[6] https://www.developerupdates.com/blog/avoid-these-7-react-useeffect-mistakes
[7] https://www.linkedin.com/pulse/useeffect-mastery-tips-tricks-avoiding-common-mistakes-novin-noori
[8] https://dev.to/hkp22/reacts-useeffect-best-practices-pitfalls-and-modern-javascript-insights-g2f
[9] https://legacy.reactjs.org/docs/hooks-effect.html
[10] https://blog.logrocket.com/useeffect-react-hook-complete-guide/
[11] https://daveceddia.com/useeffect-hook-examples/
[12] https://www.telerik.com/blogs/7-common-mistakes-using-react-hooks
[13] https://dmitripavlutin.com/react-useeffect-explanation/
[14] https://www.geeksforgeeks.org/what-are-the-pitfalls-of-using-hooks-and-how-can-you-avoid-them/
[15] https://hygraph.com/blog/react-useeffect-a-complete-guide
[16] https://blog.bitsrc.io/5-common-mistakes-when-using-useeffect-in-react-84c973060440
[17] https://www.freecodecamp.org/news/react-hooks-useeffect-usestate-and-usecontext/
[18] https://akoskm.com/common-useeffect-mistakes/
[19] https://react.dev/reference/react/useEffect
[20] https://overreacted.io/a-complete-guide-to-useeffect/
[21] https://dev.to/colocodes/6-use-cases-of-the-useeffect-reactjs-hook-282o
[22] https://www.youtube.com/watch?v=2l23TWMZFYk
[23] https://brightmarbles.io/blog/useeffect-pitfalls/
[24] https://www.epicreact.dev/myths-about-useeffect

Top comments (0)