Lädt...

🔧 useEffect: Side Effects in React


Nachrichtenbereich: 🔧 Programmierung
🔗 Quelle: dev.to

After watching myself struggle with useEffect, let me break down what's actually happening under the hood.

The Lifecycles You Need to Know

Think of your component like a house:

  • Mounting = Building the house (component first appears)
  • Rendering = Redecorating (component updates)
  • Unmounting = Demolishing (component disappears)

Here's how useEffect works with each:

function App() {
  useEffect(() => {
    console.log('🏗️ House built! (Mounted)');

    return () => {
      console.log('🏚️ House demolished! (Unmounted)');
    };
  }, []); // Empty array = only on mount/unmount

  useEffect(() => {
    console.log('🎨 Redecorating! (Re-rendered)');
  }); // No array = every render

  return <div>Hello!</div>;
}

When Effects Actually Run

Here's what happens in real life:

function RoomLight({ isOn }) {
  // 1. Runs after mount AND when isOn changes
  useEffect(() => {
    console.log(`Light turned ${isOn ? 'on' : 'off'}`);
  }, [isOn]);

  // 2. Runs after EVERY render
  useEffect(() => {
    console.log('Room redecorated');
  }); // No dependency array

  // 3. Runs ONCE after mount
  useEffect(() => {
    console.log('Room built');
  }, []); // Empty dependency array

  return <div>Room</div>;
}

Cleanup (The Important Part)

Here's when you need cleanup:

  • Timers
  • Subscriptions
  • Event listeners
  • WebSocket connections
function Timer() {
  useEffect(() => {
    // Set up
    const timer = setInterval(() => {
      console.log('Tick');
    }, 1000);

    // Clean up
    return () => {
      clearInterval(timer); // Prevents memory leaks
    };
  }, []); // Only on mount
}

function WindowWidth() {
  const [width, setWidth] = useState(window.innerWidth);

  useEffect(() => {
    // Set up
    const handleResize = () => setWidth(window.innerWidth);
    window.addEventListener('resize', handleResize);

    // Clean up
    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, []); // Only on mount
}

Common Gotchas I Hit

1. Missing Dependencies

function Counter({ start }) {
  const [count, setCount] = useState(start);

  // Wrong - doesn't update when start changes
  useEffect(() => {
    setCount(start);
  }, []); // Lint will warn you

  // Right - updates when start changes
  useEffect(() => {
    setCount(start);
  }, [start]);
}

2. Running Too Often

function Profile({ user }) {
  // Bad - new object every render
  useEffect(() => {
    console.log('Profile updated');
  }, [{ name: user.name }]); // Runs every time!

  // Good - only when name changes
  useEffect(() => {
    console.log('Profile updated');
  }, [user.name]);
}

Quick Tips

  • The cleanup function runs before the effect runs again
  • Dependencies should include everything that changes
  • Empty array = mount/unmount only
  • No array = every render
  • When in doubt, let the linter guide you

Mental Model

Think of it this way:

useEffect(() => {
  // This runs AFTER render
  console.log('Effect happened');

  return () => {
    // This runs BEFORE next effect or unmount
    console.log('Cleanup happened');
  };
}, [/* dependencies change = effect runs again */]);

That's useEffect stripped down to what matters. Still confused about something? Drop a comment - I love debugging these things.

Follow for more React tips from the trenches 🎯

...

🔧 Mastering useEffect: Handling Side Effects in React


📈 43.31 Punkte
🔧 Programmierung

🔧 React useEffect: The Power of Side Effects! ⚡


📈 43.31 Punkte
🔧 Programmierung

🔧 React useEffect: The Power of Side Effects! ⚡


📈 43.31 Punkte
🔧 Programmierung

🔧 React useEffect: The Power of Side Effects! ⚡


📈 43.31 Punkte
🔧 Programmierung

🔧 useEffect: Side Effects in React


📈 43.31 Punkte
🔧 Programmierung

🔧 useLayoutEffect vs useEffect: A Practical Guide to React Side Effects


📈 43.31 Punkte
🔧 Programmierung

🔧 🔥 Handling Side Effects in React: Beyond useEffect 🔥


📈 43.31 Punkte
🔧 Programmierung

🔧 🔥 Handling Side Effects in React: Beyond useEffect 🔥


📈 43.31 Punkte
🔧 Programmierung

🔧 🔥 Handling Side Effects in React: Beyond useEffect 🔥


📈 43.31 Punkte
🔧 Programmierung

🔧 React's useEffect Hook Simplified: Manage Side Effects Like a Pro


📈 43.31 Punkte
🔧 Programmierung

🔧 useEffect(): Making Side Effects More Manageable in React Apps Since 2019


📈 43.31 Punkte
🔧 Programmierung

🔧 Breakdown useEffect in React: Why do many people hate useEffect


📈 39.9 Punkte
🔧 Programmierung

🔧 Breakdown useEffect in React: Why do many people hate useEffect


📈 39.9 Punkte
🔧 Programmierung

🔧 Utilizing the useEffect Hook for Handling Side Effects


📈 37.63 Punkte
🔧 Programmierung

🔧 Handling Side Effects with useEffect: A Comprehensive Guide


📈 37.63 Punkte
🔧 Programmierung

🔧 UseEffect Vs. UseLayoutEffect: Why UseEffect Is a better Choice?


📈 34.21 Punkte
🔧 Programmierung

🔧 How to Handle Side Effects in Angular Using NgRx Effects


📈 33.08 Punkte
🔧 Programmierung

🔧 React's useEffect vs. useSWR: Exploring Data Fetching in React.


📈 28.47 Punkte
🔧 Programmierung

🔧 Level Up React: Mastering useEffect for performant React applications


📈 28.47 Punkte
🔧 Programmierung

🔧 From useEffect to React Query: Modernizing your data management in react


📈 28.47 Punkte
🔧 Programmierung

🔧 Best Practices for Handling Side Effects in React


📈 26.2 Punkte
🔧 Programmierung

🔧 Understanding React Hooks: Simplify State and Side Effects in Your Apps


📈 26.2 Punkte
🔧 Programmierung

🍏 Adobe After Effects 2022 23.1 - Create professional motion graphics and visual effects.


📈 25.13 Punkte
🍏 iOS / Mac OS

🔧 After Effects: Using The Essential Graphics Panel For Next Level After Effects Templates


📈 25.13 Punkte
🔧 Programmierung

🐧 TTE: Terminal Text Effects, a terminal visual effects engine


📈 25.13 Punkte
🐧 Linux Tipps

🔧 Post-Processing Effects with Shaders: Enhancing Rendered Scenes with Post-Processing Effects


📈 25.13 Punkte
🔧 Programmierung

🍏 Adobe After Effects 24.1 - Create professional motion graphics and visual effects.


📈 25.13 Punkte
🍏 iOS / Mac OS

🔧 How to Add Typing Effects to Your React App with React Typical


📈 23.93 Punkte
🔧 Programmierung