React mounts, unmounts and remounts components in Strict Mode in first render. Thereafter after for every single render Strict Mode renders the components twice, but the second render is the copy of the first so useEffect should also run once.
The code :
import React from "react";
import "./style.css";
import {useRef, useState, useEffect} from 'react';
export default function App(){
const [flag, setFlag]=useState(0);
const ref = useRef(0);
const ref2 = useRef(0);
useEffect(()=>{
ref2.current+=1;
}
)
ref.current+=1;
return(
<>
<button onClick={()=>setFlag(flag+1)}>Click</button>
<p>Number of renders without Effect : {ref.current}</p>
<p>Number of renders with Effect : {ref2.current}</p>
</>
)
}
So during initial render in Strict Mode,
1.The component mounts:
Before the JSX loads :
ref.current holds 1
ref2.current holds 0
After the JSX loads :
UI shows ref.current as 1 and ref2.current as 0
useEffect runs => ref2.current becomes 1
2.Component unmounts:
Component is erased.
3.Component Remounts:
Before the JSX loads :
ref.current holds 1
ref2.current holds 0
After the JSX loads :
UI shows ref.current as 1 and ref2.current as 0
useEffect runs => ref2.current becomes 1
So initial render in Strict mode outputs this :
Click
Number of renders without Effect : 1
Number of renders with Effect : 0
Now, if we press Click, in Strict Mode as per my understanding though the render happens twice useEffect executes once.
But now here, the UI changes to showing ref.current as 3 and ref2.current as 2. Which means useEffect has ran twice.
Now for the subsequent clicks, useEffect runs only once.
How to explain this behaviour?
Indra is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.