useEffect executes twice workaround

Reprinted from https://blog.csdn.net/SJJ980724/article/details/126144594

useEffect was executed twice. I searched for it for a long time and always thought it was a problem with my own code.

 useEffect(() => {
    console.log("useEffect调用了~");
  },[]);

Console output:

useEffect calls ~
useEffect calls ~

 After checking, I found that react18 changed the default operation of useEffect to two times .
This change will only occur in development mode, and only in strict mode. This will undoubtedly make many developers feel very annoyed.

Solution

Find the entry file main.tsx or main.jsx file and comment out the <React.StrictMode></React.StrictMode> inside.

Look again at the console output:

useEffect is called~

Guess you like

Origin blog.csdn.net/zq18877149886/article/details/130516700