Home > Web Front-end > JS Tutorial > How to Prevent `useEffect` from Running on Initial Render in React?

How to Prevent `useEffect` from Running on Initial Render in React?

Barbara Streisand
Release: 2024-11-21 04:35:11
Original
931 people have browsed it

How to Prevent `useEffect` from Running on Initial Render in React?

Preventing useEffect from Running on Initial Render

React's useEffect() hook mimics the behavior of componentDidUpdate(), including its invocation after every render. However, unlike componentDidUpdate(), useEffect() runs even on initial render. This article addresses how to rectify this issue and prevent useEffect() from executing during the initial rendering phase.

Employing the useRef Hook

To determine if useEffect() is running for the first time, utilize the useRef() hook. useRef() stores a mutable value. In this case, it can track whether it's the initial render.

Using useLayoutEffect

If the effect should occur during the same phase as componentDidUpdate(), consider using useLayoutEffect() instead of useEffect().

Example

The following code demonstrates how to prevent useEffect() from running on the initial render using useRef():

const { useState, useRef, useLayoutEffect } = React;

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

  const firstUpdate = useRef(true);
  useLayoutEffect(() => {
    if (firstUpdate.current) {
      firstUpdate.current = false;
      return;
    }

    console.log("componentDidUpdateFunction");
  });

  return (
    <div>
      <p>componentDidUpdateFunction: {count} times</p>
      <button
        onClick={() => {
          setCount(count + 1);
        }}
      >
        Click Me
      </button>
    </div>
  );
}

ReactDOM.render(<ComponentDidUpdateFunction />, document.getElementById("app"));
Copy after login

In this code:

  1. We define a component function that uses useState() to manage the count state and the useRef() hook to track the first update.
  2. We utilize useLayoutEffect() to run the effect during the same phase as componentDidUpdate().
  3. Inside the effect, we check if it's the first update (firstUpdate.current is true). If so, we set firstUpdate.current to false and return early to prevent the effect from running.

When you run this code, you'll notice that "componentDidUpdateFunction" is only logged after the initial render when the button is clicked, mimicking the behavior of componentDidUpdate().

The above is the detailed content of How to Prevent `useEffect` from Running on Initial Render in React?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template