29 мар. 2022 г.

React.StrictMode calls your render() and reducer() twice

In a strict mode development build of React renders your components twice. It calls your render() method, functional components, all the hooks two times. The reducer() function from the useReducer() hook is also called twice.

Before the second call, React disables all console output methods. In case your code works in non-strict mode but shows strange results in strict mode, you may want to see console output from the second call. In order to do that you can store the original console.log method at the very beginning of your code:

import { useReducer } from "react";
// other imports...

const log = console.log;

function MyComponent() {
  const [state, dispatch] = useReducer(reducer, undefined, init);
  log("MyComponent", state); // note: log instead of console.log
  return <div>markup...</div>;
}