Okay, I think I might as well add here that I know that code doesn't look too good, but I thought it would do the job, so I would be glad if you could explain why not only it would not be a good practice if it worked, but why it doesn't work. I'd be glad to hear your solutions to the problem too!
I'm having a hard time understanding why the chunk of code below doesn't seem to work as intended by which I mean memoizing <First />
and <Second />
functional components' return values and not calling their functions on every <App />
render. I thought that since <SomeComponent />
expression returns an object, it would be possible to simply memoize it and go with. Doesn't seem to work and I can't wrap my head around of as to why.
On a side note, I would also be thankful if you could explain why rendering <App />
component causes the renders.current
value increment by two while only calling the console.log
once.
Thanks a lot for your help!
import "./styles.css";
import React from "react";
const First = () => {
const renders = React.useRef(0);
renders.current += 1;
console.log('<First /> renders: ', renders.current);
return <h1>First</h1>;
}
const Second = () => {
const renders = React.useRef(0);
renders.current += 1;
console.log('<Second /> renders: ', renders.current);
return <h1>Second</h1>;
}
const App = () => {
const [isSwapped, setIsSwapped] = React.useState(false);
const [, dummyState] = React.useState(false);
const first = React.useMemo(() => <First />, []);
const second = React.useMemo(() => <Second />, []);
const renders = React.useRef(0);
renders.current += 1;
console.log('<App /> renders: ', renders.current);
return (
<div className="App">
<button onClick={() => setIsSwapped((isSwapped) => !isSwapped)}>Swap</button>
<button onClick={() => dummyState((state) => !state)}>Re-render</button>
{isSwapped ? (
<>
{first}
{second}
</>
) : (
<>
{second}
{first}
</>
)}
</div>
);
}
Edit: Thanks for replies, guys, this is the version that does what was intended: https://codesandbox.io/s/why-doesnt-memoization-of-a-react-functional-component-call-with-usememo-hook-forked-gvnn0?file=/src/App.js