Because you put the register logic in render function (function component's body), it will register it on every component's render.
And since you have StrictMode
wrapper, it invoked twice:
Strict mode can’t automatically detect side effects for you, but it can help you spot them by making them a little more deterministic. This is done by intentionally double-invoking the following functions:
- ...
- Function component bodies
You can either remove the StrictMode
(not recommended) or write the logic in useEffect
as I guess you want it registered on observer
change:
function Main() {
const observer = useRef(new Observer());
useEffect(() => {
observer.current.call();
}, [observer]);
return <SubComponent observer={observer.current} />;
}
Note that in StrictMode the logs are silenced, so you don't see the second console.log("registering observer");
Starting with React 17, React automatically modifies the console methods like console.log()
to silence the logs in the second call to lifecycle functions.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…