Home > Web Front-end > JS Tutorial > body text

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

DDD
Release: 2024-11-24 15:18:11
Original
554 people have browsed it

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"));
Copy after login

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"));
Copy after login

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template