Memo Example
June 23, 2021
| Content |
|---|
| React Memo |
| Memo example |
Using Memo will cause React to skip rendering a component if its props have not changed; which can help to improve performance.
Problem example
In this example, the Todos component re-renders even when the todos have not
changed.
Below, I have 2 components: App component and a Todos component. Incrementing the
count in App
component, it causes Todos component to also re-render.
Parent App component
import React, {useState} from 'react';
import Todos from './Todos'
function App() {
const [count,setCount] = useState(0)
const [todos,setTodos] = useState(['todo1', 'todo2'])
const increment = () => setCount((c) => c+ 1);
return (
<main>
<Todos todos={todos} />
<div>
Count: {count}
<button onClick={increment}>Add</button>
</div>
</main>
);
}
export default App;
Child component Todos
import React from 'react';
import './App.css';
const Todos = ({todos}) => {
console.log('child render')
return (
<div>
{todos.map((itm,idx) =>
<ul>
<li key={idx}>{itm}</li>
</ul>
)}
</div>
);
}
export default Todos;
Memo fix
So we use memo to keep the Todos component from needlessly re-rendering every time the count is incremented.
In Todos component:
• import memo from react
• wrap components export with memo
Now the Todos component only re-renders when todos props are passed
import React from 'react';
import {memo} from 'react';
const Todos = ({todos}) => {
console.log('child render')
return (
<div>
{todos.map((itm,idx) =>
<ul>
<li key={idx}>{itm}</li>
</ul>
)}
</div>
);
}
export default memo(Todos);