#react#hooks#javascript

Part 2: useEffect and Side Effects

P_

Author

Myint Myat Thein

[ status: verified_research ]

The useEffect hook is the most powerful tool in React for managing side effects. Understanding it deeply is crucial for writing effective React applications.

What are Side Effects?

Side effects are operations that interact with the outside world:

  • Fetching data from an API
  • Setting up event listeners
  • Updating the document title
  • Starting timers or subscriptions

The useEffect Hook

 import { useEffect, useState } from 'react';

function DataFetcher() {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch('/api/data')
      .then(res => res.json())
      .then(data => {
        setData(data);
        setLoading(false);
      });
  }, []); // Empty dependency array = runs once on mount

  if (loading) return <div>Loading...</div>;
  return <div>{JSON.stringify(data)}</div>;
} 

Dependency Arrays

The second argument to useEffect is the dependency array:

  • No array: Effect runs after every render
  • Empty array: Effect runs once on mount
  • With dependencies: Effect runs when any dependency changes

Common Pitfalls

One of the most common mistakes is using useState + useEffect for derived state:

 // ❌ DON'T DO THIS
const [count, setCount] = useState(0);
const [doubled, setDoubled] = useState(0);

useEffect(() => {
  setDoubled(count * 2);
}, [count]); // Extra render!

// ✅ DO THIS INSTEAD
const [count, setCount] = useState(0);
const doubled = count * 2; // Derived state = useMemo or plain computation 

In the next part, we’ll explore custom hooks and how to compose them for powerful abstractions.

References

No citations in this document.