Using Memo In ReactJS
Let's discuss on how to use memo in React, you can get to know more about memo by checking my article about on how to perfectly use React-Hooks.
Using memo will cause React to skip rendering a component if its props have not changed, and it can also improve performances.
In your index.js paste the code below.
Code Sample:
import { useState } from "react";
import ReactDOM from "react-dom";
import Todos from "./Todos";
const App = () => {
const [count, setCount] = useState(0);
const [todos, setTodos] = useState(["todo 1", "todo 2"]);
const increment = () => {
setCount((c) => c + 1);
};
return (
<>
<Todos todos={todos} />
<hr />
<div>
Count: {count}
<button onClick={increment}>+</button>
</div>
</>
);
};
ReactDOM.render(<App />, document.getElementById('root'));
Now, create a Todos.js file
in your component folder. Then, paste the code below:
const Todos = ({ todos }) => {
console.log("child render");
return (
<>
<h2>My Todos</h2>
{todos.map((todo, index) => {
return <p key={index}>{todo}</p>;
})}
</>
);
};
export default Todos;
Now you will notice that, when you click the increment button, the Todos
component re-renders. And If this component was complex, it could cause performance issues.
Now to get that fixed, we will use memo
to keep the Todos
component from needlessly re-rendering. We can do that by wrapping the Todos
component export in memo
.
In your Todos.js
add memo
to your code:
import { memo } from "react";
const Todos = ({ todos }) => {
console.log("child render");
return (
<>
<h2>My Todos</h2>
{todos.map((todo, index) => {
return <p key={index}>{todo}</p>;
})}
</>
);
};
export default memo(Todos);
You will now note that the Todos
component only re-renders when the todos that are passed to it through props are updated.