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