-
Notifications
You must be signed in to change notification settings - Fork 59
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Small optimizations #45
Conversation
This pull request is being automatically deployed with Vercel (learn more). 🔍 Inspect: https://vercel.com/michaelvasin/react-div-100vh/9rfb72gi0 |
reference https://reactjs.org/docs/hooks-reference.html#functional-updates “If your update function returns the exact same value as the current state, the subsequent rerender will be skipped completely.” Signed-off-by: KATT <[email protected]>
@@ -23,7 +23,7 @@ export default function Div100vh({ | |||
} | |||
|
|||
export function use100vh(): number | null { | |||
const [height, setHeight] = useState<number | null>(measureHeight()) | |||
const [height, setHeight] = useState<number | null>(measureHeight) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@@ -32,12 +32,12 @@ export function use100vh(): number | null { | |||
|
|||
function setMeasuredHeight() { | |||
const measuredHeight = measureHeight() | |||
if (height !== measuredHeight) setHeight(measuredHeight) | |||
setHeight(measuredHeight) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
https://reactjs.org/docs/hooks-reference.html#functional-updates
If your update function returns the exact same value as the current state, the subsequent rerender will be skipped completely.
} | ||
|
||
window.addEventListener('resize', setMeasuredHeight) | ||
return () => window.removeEventListener('resize', setMeasuredHeight) | ||
}, [height, wasRenderedOnClientAtLeastOnce]) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
skips adding/removing event listener on every resize
useEffect(() => { | ||
if (isClient() && !wasRenderedOnClientAtLeastOnce) { | ||
if (isClient()) { | ||
setWasRenderedOnClientAtLeastOnce(true) | ||
} | ||
}, [wasRenderedOnClientAtLeastOnce]) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Looks good to me, thanks @KATT! |
measureHeight()
on every render - referencereference