Skip to content

Instantly share code, notes, and snippets.

@hugows
Created December 10, 2021 17:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hugows/8df59588bc723c3a80e81fe1988d71d2 to your computer and use it in GitHub Desktop.
Save hugows/8df59588bc723c3a80e81fe1988d71d2 to your computer and use it in GitHub Desktop.
A trick to detect re-renders in React
// 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