Lab Projects
PythonReact/Next.jsBlogAbout

useEffect Hook Usage

Completed

React useEffect Hook for handling side effects like data fetching, subscriptions, and manual DOM manipulations

Difficulty:Beginner
Est. Time:15 mins
Next.js
React
SEO
Performance
Core Features:
Build-time HTML Generation
Optimal Performance, CDN Cache
Perfect SEO
No Server Overhead
Back to React ExperimentsBack to Home
🔄 useEffect Hook Practical Examples

useEffect is used for handling side effects like data fetching, subscriptions, timers, etc.

Example 1: Basic Data Fetching
useEffect(() => {}, [])

Fetch user data when component mounts (empty dependency array [])


Example 2: Timer with Cleanup Function
Cleanup Function

Create a timer with useEffect and clean it up on unmount


0

Current Count
Example 3: Dependency Array Watch Changes
useEffect(() => {}, [userId])

Re-fetch user data when user ID changes


Select User ID:

📝 useEffect Basic Syntax
// 1️⃣ Basic Usage - Run only on mount
  useEffect(() => {
    fetchData();
  }, []); // Empty array = Run once only

  // 2️⃣ With Cleanup Function - Timer/Subscription
  useEffect(() => {
    const timer = setInterval(() => {
      setCount(c => c + 1);
    }, 1000);

    // 🧹 Cleanup function
    return () => clearInterval(timer);
  }, []);

  // 3️⃣ Watch Dependency Changes
  useEffect(() => {
    fetchUser(userId);
  }, [userId]); // Re-run when userId changes

  // 4️⃣ Async Operations (Recommended Approach)
  useEffect(() => {
    const fetchData = async () => {
      const result = await api.getData();
      setData(result);
    };
    fetchData();
  }, []);
🔑 Key Points
  • Empty array [] = Run once on mount (like componentDidMount)
  • With dependencies [userId] = Re-run when dependencies change
  • No array = Run on every render (use carefully!)
  • Return cleanup function = Run on unmount or before re-run (like componentWillUnmount)
  • Async operations need async function defined inside useEffect
⚠️ Common Pitfalls
  • Forgetting to cleanup timers/subscriptions → Memory leak
  • Missing necessary dependencies → Using stale state
  • Dependencies include objects/arrays → Infinite loop
  • Using async directly in useEffect → Not recommended