React 18 useEffect Executed Twice

useEffect will execute twice in the following two cases.

Only in development mode: This is the mode used when building an application locally.

In strict mode: This is the default mode when building an application with create-react-app or Next.js.

The only way to prevent useEffect from executing twice is to turn off strict mode

In Next.js

You can disable strict mode in the next.config.js configuration file:

reactStrictMode: false


In create-react-app


import React, { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';

import App from './App';

const rootElement = document.getElementById('root'); const root = createRoot(rootElement);

root.render( <StrictMode> <App /> </StrictMode> );


<p>
    <br />
</p>
<p>
    Change to
</p>
import React from 'react';
import { createRoot } from 'react-dom/client';

import App from './App';

const rootElement = document.getElementById('root'); const root = createRoot(rootElement);

root.render( <App /> );

Author: Jiang Doufu Jing


评论

暂无评论。

登录后可发表评论。