The Magic Behind useEffect: Real-World Examples
Frontend Development
  • 18 Views

The Magic Behind useEffect: Real-World Examples

The `useEffect` hook in React is one of the most powerful tools for handling side effects in functional components. It allows developers to perform tasks like fetching data, subscribing to events, updating the DOM, or cleaning up resources. Understanding how `useEffect` works and how to use it correctly can dramatically improve the performance and behavior of your applications. In this post, we explore practical examples and common patterns for using `useEffect` in real-world projects.

Basic useEffect Example

The simplest use of `useEffect` is to run code after a component renders. For example, logging a message when a component mounts.

1import { useEffect } from 'react';
2useEffect(() => {
3  console.log('Component mounted');
4}, []);
Key Points:
  • Runs after initial render
  • Empty dependency array means it runs once
  • Useful for initialization tasks

Fetching Data from an API

A common real-world scenario is fetching data when a component mounts. Using `useEffect` ensures the fetch happens at the right time and the component updates correctly with the fetched data.

1import { useEffect, useState } from 'react';
2function Users() {
3  const [users, setUsers] = useState([]);
4  useEffect(() => {
5    fetch('https://jsonplaceholder.typicode.com/users')
6      .then(res => res.json())
7      .then(data => setUsers(data));
8  }, []);
9  return <ul>{users.map(user => <li key={user.id}>{user.name}</li>)}</ul>;
10}
Tips for API Fetching:
  • Use empty dependency array to fetch once
  • Handle loading and error states
  • Clean up if needed when component unmounts

Listening to Window Events

You can use `useEffect` to add event listeners, like tracking window resizing or scrolling, and clean them up to prevent memory leaks.

1useEffect(() => {
2  const handleResize = () => console.log(window.innerWidth);
3  window.addEventListener('resize', handleResize);
4  return () => window.removeEventListener('resize', handleResize);
5}, []);
Event Listener Best Practices:
  • Always clean up listeners to avoid memory leaks
  • Use appropriate dependencies in array
  • Consider throttling or debouncing for performance

Updating Document Title

You can use `useEffect` to update the document title based on component state, improving user experience dynamically.

1import { useEffect, useState } from 'react';
2function Counter() {
3  const [count, setCount] = useState(0);
4  useEffect(() => {
5    document.title = `Count: ${count}`;
6  }, [count]);
7  return <button onClick={() => setCount(count + 1)}>Increment</button>;
8}
Document Title Tips:
  • Add dependencies for dynamic updates
  • Avoid unnecessary renders
  • Keep it simple and descriptive

Cleanup Functions in useEffect

Some side effects require cleanup, like subscriptions or timers. Returning a function from `useEffect` ensures cleanup happens when the component unmounts or before the effect runs again.

1useEffect(() => {
2  const interval = setInterval(() => console.log('Tick'), 1000);
3  return () => clearInterval(interval);
4}, []);
Cleanup Best Practices:
  • Always clear timers or subscriptions
  • Avoid memory leaks
  • Return cleanup function inside useEffect

Conclusion

The `useEffect` hook is a versatile tool that handles side effects efficiently in React. Whether fetching data, updating the DOM, listening to events, or performing cleanup, mastering `useEffect` is essential for building robust and maintainable React applications.

Key Takeaways:
  • Understand dependency arrays and when effects run
  • Always clean up side effects when necessary
  • Use multiple useEffect hooks for clarity
  • Apply real-world patterns for common scenarios

References

Useful resources to learn more about useEffect:

Reference Links: