2

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

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Wow great spot! I found this behaviour working on a nextjs app. Console.log statements get's turned off for the double renders in Chrome (which is not the case in the virtual log in codesandbox) . which caused me to be even more confused. Thank you for your assistance

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.