This pattern is memoization with React.memo. This is known as optimization among React developer.
React.memo reuses a memoiszed component without rerendering if it is necessary in comparison between current Props and previous one.
In the demo below, even though the name state changes and the <App /> component re-renders, the props passed to the <SuperSlowComponent /> component do not change, so <SuperSlowComponent /> does not re-render.
import { memo, useState } from "react";
function SuperSlowComponent() {
const now = performance.now();
while (performance.now() - now < 200) {}
return (
<>
<div>Super slow component</div>
</>
);
}
const MemoSupserSlowComponent = memo(SuperSlowComponent);
export default function App() {
const [name, setName] = useState("");
return (
<div className="app">
<label htmlFor="name">Name</label>
<input
id="name"
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
/>
<MemoSupserSlowComponent />
</div>
);
}
Top comments (0)