🧬 React Lifecycle & Behavior
Estimated reading: 3 minutes 46 views

πŸ” React Functional Lifecycle using useEffect – Complete Guide (2025)


🧲 Introduction – Functional Lifecycle with useEffect

In class components, React used explicit lifecycle methods like componentDidMount and componentDidUpdate. In functional components, these lifecycle behaviors are implemented using the powerful useEffect hook.

With useEffect, you can handle:

  • 🧱 Mounting (componentDidMount)
  • πŸ”„ Updating (componentDidUpdate)
  • 🧹 Cleanup (componentWillUnmount)

🎯 In this guide, you’ll learn:

  • How to simulate lifecycle methods with useEffect
  • How the dependency array controls behavior
  • Examples for API calls, timers, subscriptions
  • Best practices for functional lifecycle logic

🧩 What is useEffect?

useEffect is a React Hook that runs side effects in functional components β€” such as:

  • Fetching data
  • Subscribing to events
  • Setting intervals
  • Manipulating the DOM

βœ… Syntax:

useEffect(() => {
  // side effect logic

  return () => {
    // cleanup (optional)
  };
}, [dependencies]);

🧱 1. Simulating componentDidMount – Run Once on Mount

useEffect(() => {
  console.log('Mounted once');
}, []);

βœ… The empty dependency array [] ensures the effect runs only once, after the first render β€” perfect for:

  • API requests
  • Event listeners
  • Analytics

πŸ” 2. Simulating componentDidUpdate – Run on State or Props Change

useEffect(() => {
  console.log('Count changed to:', count);
}, [count]);

βœ… This effect runs every time count changes, allowing you to:

  • React to prop changes
  • Re-run logic when state updates
  • Trigger conditional side effects

🧹 3. Simulating componentWillUnmount – Cleanup Logic

useEffect(() => {
  const timer = setInterval(() => {
    console.log('Interval tick');
  }, 1000);

  return () => {
    clearInterval(timer);
    console.log('Component unmounted');
  };
}, []);

βœ… The returned function acts as a cleanup function β€” called:

  • Before component unmounts
  • Before re-running the effect (when dependencies change)

πŸ“Š Lifecycle Summary with useEffect

Class LifecycleFunctional Equivalent
componentDidMount()useEffect(() => { ... }, [])
componentDidUpdate()useEffect(() => { ... }, [dep])
componentWillUnmount()useEffect(() => { return () => {...} }, [])

🌐 Example – Fetching Data on Mount

import { useState, useEffect } from 'react';

function UserProfile({ id }) {
  const [user, setUser] = useState(null);

  useEffect(() => {
    fetch(`/api/user/${id}`)
      .then(res => res.json())
      .then(setUser);
  }, [id]);

  return <div>{user?.name}</div>;
}

πŸ“˜ Fetches data when id changes, and re-runs only if needed


⏱️ Example – Timer with Cleanup

useEffect(() => {
  const interval = setInterval(() => {
    console.log('Tick');
  }, 1000);

  return () => clearInterval(interval);
}, []);

βœ… Runs once on mount and clears interval on unmount


⚠️ Common Pitfalls

MistakeFix
Forgetting dependency arrayEffect runs on every render
Omitting dependenciesMay cause stale or incorrect behavior
Performing async logic improperlyWrap async logic in an IIFE
Missing cleanupCan lead to memory leaks

πŸ“˜ Best Practices

βœ… Use multiple useEffect calls for unrelated logic
βœ… Always include all dependencies in the array
βœ… Use cleanup for subscriptions, intervals, and event listeners
βœ… Avoid putting effects inside conditionals or loops
βœ… Use useRef to track mounts, previous values, or internal state


πŸ“Œ Summary – Recap & Next Steps

The useEffect hook replaces class lifecycle methods in functional components. With proper use of the dependency array and cleanup, it offers powerful, clean, and flexible lifecycle management.

πŸ” Key Takeaways:

  • useEffect handles mounting, updating, and unmounting
  • Control effect behavior with dependency arrays
  • Cleanup with return function to mimic componentWillUnmount
  • Combine multiple useEffect calls to separate concerns

βš™οΈ Real-World Relevance:
From fetching user data to setting up real-time subscriptions, useEffect is used in nearly every modern React component.


❓ FAQ Section

❓ Does useEffect run after every render?
βœ… Only if you omit the dependency array. Otherwise, it depends on what values you list in [deps].


❓ How do I replicate componentWillUnmount in functional components?
βœ… Use the return statement in useEffect:

useEffect(() => {
  return () => {
    console.log('Cleanup');
  };
}, []);

❓ Can I use multiple useEffect() hooks in one component?
βœ… Yes! It’s a best practice to separate effects by concern.


❓ Can useEffect be async?
❌ No, but you can define an async function inside:

useEffect(() => {
  (async () => {
    await fetchData();
  })();
}, []);

❓ What if I forget a dependency?
⚠️ Your effect might use stale values. Use eslint-plugin-react-hooks to catch missing dependencies.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

πŸ” React Functional Lifecycle using useEffect

Or Copy Link

CONTENTS
Scroll to Top