As far as I understand, React.memo is an API that memoize a component: if its props don't change, react use the latest render of that component without comparing it with its previous version. Skipping new render and comparing with old one speed-up the app. Cool.
Now, here's what I don't get: if props don't change, also a not memoized component don't get re-rendered, as I can see from that simple code (use this link to see the demo, the code snippet on this page is a little bit confusing): there's no difference about number of renders between a normal component+usecallback and a memoized one+useCallback. Basically, useCallbacks is all I need, as a normal component doesn't get re-rendered with same props. Then, what I'm I missing? When memo comes in help to optimize?
const { useCallback, useEffect, useState, memo, useRef } = React;
function Child({ fn, txt }) {
const [state, setState] = useState(0);
console.log(txt + " rendered!");
useEffect(() => {
setState((state) => state + 1);
}, [fn]);
return (
<div style={{ border: "solid" }}>
I'm a Child
{!fn && <div>And I got no prop</div>}
{fn && <div>And I got a fn as a prop</div>}
<div>
and I've got rendered <strong>{state}</strong> times
</div>
</div>
);
}
const MemoChild = memo(Child);
function App() {
const [, setState] = useState(true);
const handlerOfWhoKnows = () => {};
return (
<div className="App">
I'm the parent
<br />
<button onClick={() => setState((state) => !state)}>
Change parent state
</button>
<h3>Ref</h3>
ref: <Child txt="ref" fn={handlerOfWhoKnows} />
<h3>test</h3>
useCB: <Child txt="useCb" fn={useCallback(handlerOfWhoKnows, [])} />
memo: <MemoChild txt="memo" fn={handlerOfWhoKnows} />
memo + useCB: <MemoChild txt="memo+useCb" fn={useCallback(handlerOfWhoKnows, [])} />
</div>
);
}
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>