DEV Community

Madhavan G
Madhavan G

Posted on

Understanding useEffect in React with Simple Examples

React’s useEffect hook is one of the most important hooks for handling side effects in functional components.

You can use it to:

  1. run code after rendering
  2. fetch data
  3. listen to changes
  4. work with timers
  5. update the DOM and much more.

The behavior of useEffect mainly depends on its dependency array.

Let’s understand it with practical examples.


1. Run Only Once (Component Mount)

Sometimes you want code to run only when the page loads for the first time.

Example:

  • API call on page load
  • Initial setup
  • Logging

Example:

import React, { useEffect } from "react";

function App() {
  useEffect(() => {
    console.log("Component Mounted");
  }, []);

  return <h1>Hello React</h1>;
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Why Does This Work?

An empty dependency array tells React:

“Run this effect only once after the initial render.”

Output:
Component Mounted

Only once when the component loads.


2. Run on Every Render:

Sometimes you want something to happen after every render.

Example:

import React, { useEffect, useState } from "react";

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

  useEffect(() => {
    console.log("Rendered");
  });

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

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

export default App;
Enter fullscreen mode Exit fullscreen mode

What Happens Here?

Since no dependency array is provided:

the effect runs after every render

This includes:

  • initial render
  • state updates
  • parent component re-renders

Output:

Rendered
Rendered
Rendered

Every render triggers the effect.

Important Note

Be careful with this pattern because unnecessary renders can affect performance.


3. Run When State Changes:

Suppose you want an effect to run only when a specific state changes.

Example:

import React, { useEffect, useState } from "react";

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

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

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

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

export default App;

Enter fullscreen mode Exit fullscreen mode

What Happens?

Dependency Array
[count]
So the effect runs whenever count changes.


4. Two States, One Effect:

Now let’s say we have two state variables.

Example:

import React, { useEffect, useState } from "react";

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

  useEffect(() => {
    console.log("Effect ran");
  }, [count, name]);

  return (
    <div>
      <input
        type="text"
        placeholder="Enter name"
        value={name}
        onChange={(e) => setName(e.target.value)}
      />

      <h1>{count}</h1>

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

export default App;
Enter fullscreen mode Exit fullscreen mode

What Happens?

The effect runs whenever:

count changes
OR name changes
Why?

React watches all values inside the dependency array.

If any dependency changes, the effect runs again.

What If Only count Is Added?
useEffect(() => {
console.log("Effect ran");
}, [count]);

Now:

changing count triggers the effect
changing name does NOT trigger the effect

This can sometimes create bugs if your effect also depends on name.


5. Derived Logic — Should It Be Inside useEffect?:

Suppose we want to show:

“Even Number”

whenever count becomes even.

Example:

import React, { useState } from "react";

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

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

      {count % 2 === 0 && <p>Even Number</p>}

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

export default App;
Enter fullscreen mode Exit fullscreen mode

Why Not useEffect?

Because this is:

  • derived UI
  • not a side effect

useEffect should be used only for side effects like:

  • API calls
  • timers
  • subscriptions
  • localStorage updates

Top comments (0)