EN
React - how to use memo
10 points
In this article we would like show you how to use memo function in React.
Note:
React.memo()
guarantees that a component will be re-rendered only if props are changed for the component - it is used to boost performance of a application.
Below example shows two functional components - NormalComponent
and MemoComponent
.
The MemoComponent
was created with React.memo()
, which means React renders component only on the MemoComponent
props change - in our case it doesn't have props, so it will be rendered only once at begining.
In the example we set a counter
to display how many times each element was rendered.
Runnable example:
xxxxxxxxxx
1
//Note: Uncomment import lines during working with JSX Compiler.
2
// import React from react';
3
4
const NormalComponent = () => {
5
const counterRef = React.useRef(0);
6
console.log(`--- [Normal Component] rendering: counter=${++counterRef.current}`);
7
return <div>[Normal Component]</div>;
8
};
9
10
const MemoComponent = React.memo(() => {
11
const counterRef = React.useRef(0);
12
console.log(`--- [Memo Component] rendering: counter=${++counterRef.current}`);
13
return <div>[Memo Component]</div>;
14
});
15
16
const App = () => {
17
const [counter, setCounter] = React.useState(1);
18
console.log(`- [App] rendering: counter=${counter}`);
19
return (
20
<div>
21
<NormalComponent />
22
<MemoComponent />
23
<button onClick={() => setCounter(counter + 1)}>Click me!</button>
24
</div>
25
);
26
};
27
28
const root = document.querySelector('#root');
29
ReactDOM.render(<App />, root );