Skip to content

Instantly share code, notes, and snippets.

@acro5piano
Created April 28, 2021 11:20
Show Gist options
  • Save acro5piano/fc7c5ec572428f8e4e324967109de558 to your computer and use it in GitHub Desktop.
Save acro5piano/fc7c5ec572428f8e4e324967109de558 to your computer and use it in GitHub Desktop.
react re-render test for children prop
import { memo, useState, useMemo } from 'react'
const MODE = 'memo'
function MiddleRaw({ children }) {
console.log('middle')
return <div>{children}</div>
}
const Middle = memo(MiddleRaw)
function ChildRaw() {
console.log('child')
return <div>I am child</div>
}
const Child = memo(ChildRaw)
export default function App() {
const [count, setCount] = useState(0)
console.log('app')
const memoizedChildren = useMemo(
() => (
<Middle>
<Child />
</Middle>
),
[],
)
// logs "app", "middle", "child" on every re-render
if (MODE === 'plain') {
return (
<div className="App">
<button onClick={() => setCount(count + 1)}>count up</button>
<MiddleRaw>
<ChildRaw />
</MiddleRaw>
</div>
)
}
// logs "app", "middle" on every re-render
if (MODE === 'memo') {
return (
<div className="App">
<button onClick={() => setCount(count + 1)}>count up</button>
<Middle>
<Child />
</Middle>
</div>
)
}
// logs "app" on every re-render
if (MODE === 'useMemo') {
return (
<div className="App">
<button onClick={() => setCount(count + 1)}>count up</button>
{memoizedChildren}
</div>
)
}
return null
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment