Mern Stack

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

Ziaul Kabir
โ€ขโ€ข1 min read
Learn React useEffect Hook with LyzersLab - A Beginner's Guide to Side Effects in React

๐Ÿ”น 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

Written by

Ziaul Kabir

Share:

Comments (0)

No comments yet. Be the first to comment!