Using memo causes React to skip rendering a component if its props have not updated.
This can boost performance.
This section utilizes React Hooks. Hooks are discussed in further detail in the React Hooks section.
In this example, the Todos component re-renders even though the todos have not changed.
index.js:
Todos.js:
const Todos = ({ todos }) => {
console.log("child render");
return (
<>
My Todos
{todos.map((todo, index) => {
return {todo}
;
})}
>
);
};
export default Todos;
When you click the increment button, the Todos component reloads.
If this component was complex, it may lead to performance concerns.
To address this, we can use memo.
Use memo to prevent the Todos component from repeatedly re-rendering.
Wrap the Todos component export with a memo.
index.js:
Todos.js:
import { memo } from "react";
const Todos = ({ todos }) => {
console.log("child render");
return (
<>
My Todos
{todos.map((todo, index) => {
return {todo}
;
})}
>
);
};
export default memo(Todos);
Now, the Todos component only re-renders when the todos supplied to it via props change.
CodingAsk.com is designed for learning and practice. Examples may be made simpler to aid understanding. Tutorials, references, and examples are regularly checked for mistakes, but we cannot guarantee complete accuracy. By using CodingAsk.com, you agree to our terms of use, cookie, and privacy policy.
Copyright 2010-2024 by Refsnes Data. All Rights Reserved.