DEV Community

Sajin Joe J
Sajin Joe J

Posted on

React: useEffect()

1. What is useEffect?
useEffect() is used to perform side effects in a React component.

A side effect is an operation that happens outside the normal rendering process.

Examples:

  • Fetching API data
  • Setting a timer
  • Adding an event listener
  • Updating the browser tab title
  • Subscribing to an event

Basic syntax

useEffect(() => {
    // Your code
}, [dependencies]);
Enter fullscreen mode Exit fullscreen mode

There are two important parts:
() => {} -Effect function
[] -Dependency array

Let's learn what the dependency array does.

2. Three types of useEffect

Type 1: Run only once — []

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

Output:

Component Mounted
Enter fullscreen mode Exit fullscreen mode
  • Runs after the component initially mounts.
  • Does not run again on ordinary re-renders.
  • Useful for fetching API data on mount.

Type 2: Run when state changes — [count]

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

Output when count increases from 0 to 3:

Count changed: 0
Count changed: 1
Count changed: 2
Count changed: 3
Enter fullscreen mode Exit fullscreen mode
  • Runs after initial mount.
  • Runs again whenever count changes.

Type 3: Run on every render — no dependency array

useEffect(() => {
    console.log("Rendered");
});
Enter fullscreen mode Exit fullscreen mode

Output:

Rendered
Rendered
Rendered
Rendered
Enter fullscreen mode Exit fullscreen mode

It runs after every render.

3. Complete React example
This example demonstrates useState + useEffect.

import { useState, useEffect } from "react";

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

    useEffect(() => {
        console.log("Count changed:", count);
    }, [count]);

    return (
        <div>
            <h1>Count: {count}</h1>

            <button onClick={() => setCount(count + 1)}>
                Increment
            </button>
        </div>
    );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Top comments (0)