React useEffect Hooks

🔥 React useEffect Hook

The useEffect Hook allows you to perform side effects in functional components.

📌 A side effect is anything that happens outside the normal UI rendering, such as:

  • Fetching API data

  • Using setTimeout or setInterval

  • Updating the document title

  • Working with browser storage

  • Adding event listeners

Before Hooks, these tasks were done in class lifecycle methods:

Class ComponentEquivalent with Hooks
componentDidMount()useEffect(() => {}, [])
componentDidUpdate()useEffect(() => {})
componentWillUnmount()Cleanup inside effect

🧪 Basic Example


 

export default App;

📍 This effect runs after every render, including state changes.


🎯 Run Effect Only Once (Like componentDidMount)

Add an empty dependency array []:

Useful for:

✔ Fetching data
✔ Setting up listeners
✔ Initial setup logic


🎯 Run Effect Only When Specific Value Changes

➡ This runs the effect only when count changes, not on every render.


🧹 Cleanup Function (Unmount Logic)

Use cleanup to remove timers, listeners, etc.


 

➡ Executes when component unmounts or before re-running effect.


Example: Timer with Cleanup


 


🌐 Fetch API Example


⚠️ Rules & Notes

RuleExplanation
Must be called at top levelNo loops, conditions, or nested functions
Runs after renderReact first paints UI, then runs effect
Cleanup prevents memory leaksRequired when using timers/listeners

🔍 Summary Table

DependencyWhen Effect Runs
No arrayAfter every render
[] empty arrayOnly once (on mount)
[value]Only when value changes
Cleanup return functionOn unmount or before next run

🎉 Example Putting It All Together


 

You may also like...