When to use useEffect?

Please refer below content for more clarity. You might have missed reading that after copying code from official document.

Example Using Hooks

What does useEffect do?

By using this Hook, you tell React that your component needs to do something after render. React will remember the function you passed (we’ll refer to it as our “effect”), and call it later after performing the DOM updates. In this effect, we set the document title, but we could also perform data fetching or call some other imperative API.

Why is useEffect called inside a component?

Placing useEffect inside the component lets us access the count state variable (or any props) right from the effect. We don’t need a special API to read it — it’s already in the function scope. Hooks embrace JavaScript closures and avoid introducing React-specific APIs where JavaScript already provides a solution.

Does useEffect run after every render?

Yes! By default, it runs both after the first render and after every update. (We will later talk about how to customize this.) Instead of thinking in terms of “mounting” and “updating”, you might find it easier to think that effects happen “after render”. React guarantees the DOM has been updated by the time it runs the effects.


You showed two different examples,

handleButtonClick fires on Button 1 click, while useEffect fires on every state change state (according to the dependency array).

In the next example, you notice that useEffect will log on every button click (Button 1/2), and handleButtonClick will log only on Button 2 click.

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

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

  useEffect(() => {
    console.log(`You rendered ${count} times`);
  }, [count]);

  const handleButtonClick = () => {
    setCount(count + 1);
    console.log(`You clicked ${count + 1} times`);
  };

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Button 1</button>
      <button onClick={handleButtonClick}>Button 2</button>
    </div>
  );
}
  • Check similar question on useEffect use cases
  • Refer to useEffect docs

The idea to use useEffect hook is to execute code that needs happens during lifecycle of the component instead of on specific user interactions or DOM events.

For instance, you wish to set a timer that executes a code when the component is rendered initially or as done in your initial example, the document title is updated when the component mounts, there is no user interaction associated here

useEffect is an alternative for lifecycle method in class components in a functional component. It can be used to execute actions when the component mounts, or certain prop or state updated for component as well as to execute code when the component is about to unmount

Tags:

Reactjs