React question detail
Why does strict mode render twice in React?
StrictMode renders components twice in development mode(not production) in order to detect any problems with your code and warn you about those problems. This is used to detect accidental side effects in the render phase. If you used create-react-app development tool then it automatically enables StrictMode by default.
const root = createRoot(document.getElementById("root"));
root.render(
<StrictMode>
<App />
</StrictMode>
);
If you want to disable this behavior then you can simply remove strict mode.
const root = createRoot(document.getElementById("root"));
root.render(<App />);
To detect side effects the following functions are invoked twice:
- Function component bodies, excluding the code inside event handlers.
- Functions passed to
useState,useMemo, oruseReducer(any other Hook) - Class component's
constructor,render, andshouldComponentUpdatemethods - Class component static
getDerivedStateFromPropsmethod - State updater functions