Created
April 27, 2023 21:53
-
-
Save Shalabyelectronics/a1dde3ae3240dfc18814b73979600c46 to your computer and use it in GitHub Desktop.
Practice React memo, useMemo and useCallback
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState, memo, useMemo, useCallback } from "react"; | |
function Box({ color, onClick }) { | |
console.log(`Box color : ${color.color}`); | |
return ( | |
<div | |
style={{ | |
margin: 10, | |
width: 75, | |
height: 75, | |
backgroundColor: color.color, | |
}} | |
onClick={onClick} | |
></div> | |
); | |
} | |
const MemoBox = memo(Box); | |
function App() { | |
const [appRender, setAppRender] = useState(0); | |
const [color, setColor] = useState("red"); | |
const onClick = useCallback(() => {}, []); | |
console.log(`App re-render : ${appRender}`); | |
const colorObj = useMemo( | |
() => ({ | |
color, | |
}), | |
[color] | |
); | |
return ( | |
<> | |
<button onClick={() => setAppRender((prevState) => prevState + 1)}> | |
App re-render | |
</button> | |
<button onClick={() => setColor(color === "red" ? "blue" : "red")}> | |
Switch Color | |
</button> | |
<MemoBox color={colorObj} onClick={onClick} /> | |
</> | |
); | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment