0
0
ReactHow-ToBeginner · 4 min read

How to Use useEffect in React: Simple Guide with Examples

In React, useEffect runs code after rendering to handle side effects like fetching data or updating the DOM. You use it by passing a function and an optional dependency array to control when it runs.
📐

Syntax

The useEffect hook takes two arguments: a function to run after render, and an optional array of dependencies that control when the effect runs.

  • useEffect(() => { ... }, [dependencies])
  • The function runs after the component renders.
  • If the dependency array is empty, it runs only once after the first render.
  • If omitted, it runs after every render.
javascript
useEffect(() => {
  // code to run after render
}, [dependencies]);
💻

Example

This example shows how to use useEffect to update the document title whenever the count changes.

javascript
import React, { useState, useEffect } from 'react';

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

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

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

export default Counter;
Output
You clicked 0 times (button shown). Clicking the button updates the count and document title.
⚠️

Common Pitfalls

Common mistakes include:

  • Not providing a dependency array, causing the effect to run after every render and possibly causing performance issues.
  • Including changing objects or functions in dependencies without memoization, causing infinite loops.
  • Forgetting to clean up subscriptions or timers inside the effect, which can cause memory leaks.
javascript
import React, { useState, useEffect } from 'react';

// Wrong: effect runs every render causing infinite loop
function Wrong() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    setCount(count + 1); // updates state inside effect
  });

  return <p>{count}</p>;
}

// Right: use empty dependency array to run once
function Right() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    setCount(1);
  }, []);

  return <p>{count}</p>;
}
📊

Quick Reference

Remember these tips when using useEffect:

  • Use dependency array to control when effect runs.
  • Clean up side effects by returning a function inside useEffect.
  • Keep effects focused on one task.
  • Avoid updating state inside effect without dependencies to prevent loops.

Key Takeaways

Use useEffect to run code after rendering for side effects like data fetching or DOM updates.
Always provide a dependency array to control when the effect runs and avoid unnecessary executions.
Clean up effects by returning a cleanup function to prevent memory leaks.
Avoid updating state inside effects without proper dependencies to prevent infinite loops.
Keep effects simple and focused on one task for easier maintenance.