Skip to content

Instantly share code, notes, and snippets.

@Shalabyelectronics
Created April 27, 2023 21:53
Show Gist options
  • Save Shalabyelectronics/a1dde3ae3240dfc18814b73979600c46 to your computer and use it in GitHub Desktop.
Save Shalabyelectronics/a1dde3ae3240dfc18814b73979600c46 to your computer and use it in GitHub Desktop.
Practice React memo, useMemo and useCallback
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