-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReact-Memo.js
33 lines (25 loc) · 938 Bytes
/
React-Memo.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import React, { useState, useCallback } from "react";
const App = () => {
const [count, setCount] = useState(0);
// useCallback - so it will prevent to re-render unnecessarily from child component.
const increment = useCallback(() => {
// Here note, previously it was setCount(count + 1), now it was changed to prevCount => prevCount + 1
setCount(prevCount => prevCount + 1);
}, []);
return (
<>
<span>Count: {count}</span>
<button onClick={increment}>Increment</button>
<ChildMemo onClick={increment} />
</>
);
}
// Make the child component as "Memo", here memo is hight order component.
const Child = ({ onClick }) => {
console.log("child is re-rendered");
return <>
<button onClick={onClick}>Child button</button>
</>
}
const ChildMemo = React.memo(Child);
export default App;