Home > front end >  React component is calling memo function twice
React component is calling memo function twice

Time:08-06

If i create a React component like so:

import { useMemo } from "react";

let id = 0;

function updateLogAndGetId() {
  const newId = id  ;
    console.log(newId);
    return newId;
}

export const MyComponent = () => {
  const componentId = useMemo(updateLogAndGetId, []);
  console.log("outside", componentId);
  return <li>{componentId}</li>;
};

render(<><MyComponent /><MyComponent /></>)

The HTML output will be: 1 3

the console output would be: 0 1 2 3

Why is it that the updateLogAndGetId is invoked 4 times, when only two components are added to the dom?

Are there any way to ensure that updateLogAndGetId is only invoked once pr component?

Here as a sandbox with a working example: https://codesandbox.io/s/dreamy-dream-rti4tp

CodePudding user response:

The React StrictMode renders components twice on development (not production)

// your index.tsx :
import { StrictMode } from "react";
import * as ReactDOMClient from "react-dom/client";
import App from "./App";

const rootElement = document.getElementById("root");
const root = ReactDOMClient.createRoot(rootElement);

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

you can remove it and test your console.log again

// your index.tsx :
import * as ReactDOMClient from "react-dom/client";
import App from "./App";

const rootElement = document.getElementById("root");
const root = ReactDOMClient.createRoot(rootElement);

// render your App component without the StrictMode :
root.render(
    <App />
);

more about React StrictMode

  • Related