DEV Community

Cover image for Simplifying React Hooks: useEffect πŸ’―
Ali Samir
Ali Samir

Posted on

Simplifying React Hooks: useEffect πŸ’―

React Hooks revolutionized how developers handle state and side effects in functional components. useEffect is one of the most powerful but often misunderstood hooks.

In this article, we will break down useEffect, simplify its use, and provide best practices to optimize your React applications.


Understanding useEffect ✍🏻

The useEffect hook allows you to perform side effects in function components. Side effects include data fetching, subscriptions, manual DOM manipulations, and more.

Basic Syntax:

import { useEffect } from "react";

useEffect(() => {
  // Side effect logic here
});
Enter fullscreen mode Exit fullscreen mode

Dependencies and Execution βš™οΈ

1. Running on Every Render (No Dependency Array)

If you omit the dependency array, the effect will execute on every render.

useEffect(() => {
  console.log("Component re-rendered!");
});
Enter fullscreen mode Exit fullscreen mode

2. Running Once on Mount (Empty Dependency Array)

Adding an empty dependency array ([]) makes useEffect run only once when the component mounts.

useEffect(() => {
  console.log("Component mounted!");
}, []);
Enter fullscreen mode Exit fullscreen mode

3. Running When Dependencies Change

You can specify dependencies inside the array. The effect will run only when those values change.

const [count, setCount] = useState(0);

useEffect(() => {
  console.log(`Count changed: ${count}`);
}, [count]);
Enter fullscreen mode Exit fullscreen mode

Cleaning Up Effects ⚑

If an effect involves a subscription or a long-running process, you should clean it up to avoid memory leaks.

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

  return () => {
    clearInterval(interval);
    console.log("Cleanup on unmount");
  };
}, []);
Enter fullscreen mode Exit fullscreen mode

Common Pitfalls & Best Practices βœ…

1. Avoid Unnecessary Re-Renders

Make sure to include only necessary dependencies to prevent unwanted effect executions.

useEffect(() => {
  fetchData();
}, [userId]); // Only runs when userId changes
Enter fullscreen mode Exit fullscreen mode

2. Use Custom Hooks for Complex Logic

If an effect grows in complexity, consider extracting it into a custom hook.

function useDocumentTitle(title: string) {
  useEffect(() => {
    document.title = title;
  }, [title]);
}

useDocumentTitle("My Custom Title");
Enter fullscreen mode Exit fullscreen mode

3. Handle Asynchronous Effects Properly

If your effect includes an async function, define it inside the effect or use an IIFE (Immediately Invoked Function Expression).

useEffect(() => {
  (async () => {
    const data = await fetchData();
    setState(data);
  })();
}, []);
Enter fullscreen mode Exit fullscreen mode

Conclusion πŸ’―

useEffect is a fundamental hook for handling side effects in React, but it must be used with caution to avoid performance issues and unnecessary re-renders.

Understanding its execution flow, dependencies, and cleanup process will help you write efficient and maintainable React applications.

By following best practices, refactoring into custom hooks when needed, and handling dependencies correctly, you can harness the full power of useEffect without the common pitfalls.


🌐 Connect With Me On:

πŸ“ LinkedIn
πŸ“ X (Twitter)
πŸ“ Telegram
πŸ“ Instagram

Happy Coding!

Top comments (0)