Created
December 10, 2021 17:00
-
-
Save hugows/8df59588bc723c3a80e81fe1988d71d2 to your computer and use it in GitHub Desktop.
A trick to detect re-renders in React
This file contains hidden or 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
// Add a random background to the component | |
// On a re-render, the component gets a new color | |
// Source of this snippet: https://kyleshevlin.com/using-react-memo-to-avoid-unnecessary-rerenders | |
const random255 = () => Math.floor(Math.random() * 255) | |
const randomRGBA = () => { | |
const r = random255() | |
const g = random255() | |
const b = random255() | |
return `rgba(${r}, ${g}, ${b}, 0.3)` | |
} | |
function Profile({ name, location }) { | |
return ( | |
<div style={{ backgroundColor: randomRGBA() }}> | |
<div>{name}</div> | |
<div>{location}</div> | |
</div> | |
) | |
} | |
const MemoizedProfile = React.memo(Profile) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment