React useEffect Hook
⏱ Estimated reading time: 2 min
The useEffect hook lets you perform side effects in functional components. Side effects include data fetching, subscriptions, timers, DOM updates, and logging.
What is useEffect?
-
Runs after render
-
Replaces lifecycle methods like
componentDidMount,componentDidUpdate, andcomponentWillUnmount -
Helps keep side-effect logic organized
Basic Syntax
1. Run on Every Render
-
No dependency array
-
Runs after every render
2. Run Once (On Mount)
-
Empty dependency array
-
Runs only once when component mounts
3. Run When Dependencies Change
-
Runs when
countchanges
Common Use Cases
Fetching Data
Updating Document Title
Timers
Cleanup Function
Use cleanup to avoid memory leaks.
Dependency Array Rules
-
Include all values used inside
useEffect -
React compares dependencies using shallow comparison
-
Missing dependencies can cause bugs
Common Mistakes
❌ Forgetting dependency array
❌ Incorrect dependencies
❌ Infinite loops due to state updates
Best Practices
-
Use multiple
useEffecthooks for different logic -
Keep effects small and focused
-
Always clean up subscriptions and timers
Key Points
-
useEffecthandles side effects -
Dependency array controls when it runs
-
Cleanup prevents memory leaks
-
Essential for real-world React apps
Register Now
Share this Post
← Back to Tutorials