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

How to Prevent the React useEffect Hook from Running on Initial Render?

DDD
DDDOriginal
2024-11-24 15:18:11615browse

How to Prevent the React useEffect Hook from Running on Initial Render?

Preventing the React useEffect Hook from Running on Initial Render

The useEffect hook is a valuable tool for managing side effects in React components. However, by default, it runs after every render, including the initial one. This can lead to unwanted behavior, as illustrated by the example code. To overcome this, there are two effective strategies.

1. Using the useRef Hook to Track Initial Render

The useRef hook allows us to store a mutable value that persists across re-renders. By leveraging this, we can keep track of whether it's the first time the useEffect function is executed.

Example:

const { useState, useRef, useEffect } = React;

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

  const firstUpdate = useRef(true);
  useEffect(() => {
    // Skip the initial render
    if (firstUpdate.current) {
      firstUpdate.current = false;
      return;
    }

    console.log("useEffect ran");
  });

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

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

2. Utilizing the useLayoutEffect Hook

The useLayoutEffect hook is introduced to simulate the behavior of componentDidUpdate in terms of the execution phase. It runs before the browser paints, preventing any visual glitches.

Example:

const { useState, useLayoutEffect } = React;

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

  useLayoutEffect(() => {
    console.log("useLayoutEffect ran");
  });

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

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

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

Statement:
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