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

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

Barbara Streisand
Barbara StreisandOriginal
2024-11-21 05:37:13577browse

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

Making React's useEffect Hook Avoid Initial Render Execution

The componentDidUpdate() lifecycle method in class-based React components is invoked after each render, except for the initial one. To emulate this behavior with the useEffect hook, it may appear that the hook is running on every render, including the first time.

Solution

To prevent useEffect from running on initial render, utilizing the useRef hook can help track whether it's the initial invocation of the effect.

Furthermore, to mimic the behavior of componentDidUpdate, which runs in the "layout effects" phase, consider using useLayoutEffect instead of useEffect.

Example

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")
);

This approach employs the useRef hook to track the first update and ensures that the effect only executes during subsequent updates, mirroring the behavior of componentDidUpdate in class-based components.

The above is the detailed content of How to Prevent useEffect Hook from Running on Initial Render in React?. 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