useEffect in React: Your Personal Assistant for Side Effects!

  

 

  

"useEffect is like a personal assistant in React – ready to do stuff whenever you say 'Hey, something changed!'"

Hello JSX sorcerers! 

If you’ve already met useState and started getting comfy managing data inside your components, it’s time to level up. Say hello to useEffect() – your ultimate tool for handling side effects in React!

 

What is useEffect?

useEffect is a React Hook that lets you perform side effects in function components.

Side effects in React can be things like:

  • Fetching data from an API
  • Setting up a timer or interval
  • Updating the document title
  • Reading/writing to localStorage
  • Subscribing to browser events like scroll or resize

 

Basic Syntax

useEffect(() => {
  // code to run
}, [dependencies]);

The second argument (array) controls when the effect runs.

 

Run Once (Like componentDidMount)

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

 

Run on Dependency Change

useEffect(() => {
  console.log(`Name changed to: ${name}`);
}, [name]);

 

No Dependency Array = Run Every Render

Be careful – if you omit the array, useEffect runs on every render!

 

Example: Fetch Data Once

useEffect(() => {
  fetch('/api/data')
    .then((res) => res.json())
    .then((data) => console.log(data));
}, []);

 

Example: Timer with Cleanup

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

  return () => {
    clearInterval(interval);
    console.log('cleanup');
  };
}, []);

 

Dynamic Document Title

useEffect(() => {
  document.title = `Clicked ${count} times`;
}, [count]);

 

Common Mistakes

  •  Missing dependency array: causes re-run on every render
  •  Wrong dependencies: can skip updates or cause bugs
  •  No cleanup: can lead to memory leaks
  •  Using async directly in useEffect: not allowed

 

Correct async usage:

useEffect(() => {
  const fetchData = async () => {
    const res = await fetch('/api');
  };
  fetchData();
}, []);

 

Real-World Example: Connection Status

function ConnectionStatus() {
  const [isOnline, setIsOnline] = useState(navigator.onLine);

  useEffect(() => {
    const handleOnline = () => setIsOnline(true);
    const handleOffline = () => setIsOnline(false);

    window.addEventListener('online', handleOnline);
    window.addEventListener('offline', handleOffline);

    return () => {
      window.removeEventListener('online', handleOnline);
      window.removeEventListener('offline', handleOffline);
    };
  }, []);

  return <p>Status: {isOnline ? 'Online' : 'Offline'}</p>;
}

 

LocalStorage Sync Example

function Notes() {
  const [note, setNote] = useState('');

  useEffect(() => {
    const saved = localStorage.getItem('note');
    if (saved) setNote(saved);
  }, []);

  useEffect(() => {
    localStorage.setItem('note', note);
  }, [note]);

  return (
    <textarea
      value={note}
      onChange={(e) => setNote(e.target.value)}
    />
  );
}

 

Class vs useEffect Lifecycle Comparison

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

 

Tips

  •  Use multiple useEffect blocks for unrelated logic
  •  Keep effect logic clean and focused
  •  Use cleanup wisely for intervals, subscriptions, etc.
  •  Install eslint-plugin-react-hooks for safety checks

useEffect is a powerful tool that lets your React components interact with the world outside the UI. From fetching APIs to handling events, this hook is your go-to method for side effects.

"React is about the UI. useEffect is about what happens around it."

 

 

 

0 Comments:

Post a Comment