Learn React useEffect Hook with LyzersLab – A Beginner's Guide to Side Effects in React

Learn React useEffect Hook with LyzersLab – A Beginner's Guide to Side Effects in React
Category:Mern Stack
Tags:
JavaScriptJSMern StackNext.jsReactuseEffect hook
Published:May 6, 2025

Share this post:

πŸ”Ή React Hook Deep Dive: useEffect Made Simple

Our format stays strong:

  1. βœ… Core Concept
  2. πŸ“˜ Real Example
  3. 🧠 Best Practices
  4. ⚠️ Pitfalls to Avoid
  5. πŸ”„ Execution Order
  6. πŸ§ͺ Optional Demo (CodeSandbox or Timeline)

βœ… 1. Concept

useEffect lets you perform side effects in function components β€” like data fetching, subscriptions, DOM updates, or timers.

It runs after render, and can optionally clean up.

useEffect(() => {
  // run side effect
  return () => {
    // optional cleanup
  };
}, [dependencies]);

πŸ“˜ 2. Example: Fetching Data on Mount

import React, { useEffect, useState } from 'react';

function Users() {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/users')
      .then(res => res.json())
      .then(data => setUsers(data));
  }, []); // empty array = run once on mount

  return (
    <ul>
      {users.map(user => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );
}

This runs once after initial render and fetches user data.

🧠 3. Best Practices

  • βœ… Use multiple useEffects for unrelated concerns
  • βœ… Always define dependencies correctly
  • βœ… Return a cleanup function if needed (like removing event listeners)
  • βœ… Use async functions inside the effect, not at the top level
useEffect(() => {
  const load = async () => {
    const res = await fetch(...);
    const data = await res.json();
    setData(data);
  };
  load();
}, []);

⚠️ 4. Common Pitfalls

  • ❌ Forgetting dependencies β†’ stale state or bugs
  • ❌ Using async directly in useEffect (it returns a promise, not a cleanup)
  • ❌ Not cleaning up subscriptions β†’ memory leaks

πŸ”„ 5. Execution Order

Step Phase What Happens
1 Render Component mounts
2 Commit DOM updates
3 Post-render useEffect runs
4 Re-render Runs again if deps changed
5 Unmount Cleanup (if defined) runs
zkrana

Ziaul Kabir

Website Specialist

May 6, 2025

Comments (0)

No comments yet. Be the first to comment!