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"));
In this code:
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!