Skip to content
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

Merged
merged 2 commits into from
Sep 25, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions packages/react-div-100vh/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.


const wasRenderedOnClientAtLeastOnce = useWasRenderedOnClientAtLeastOnce()

Expand All @@ -32,12 +32,12 @@ export function use100vh(): number | null {

function setMeasuredHeight() {
const measuredHeight = measureHeight()
if (height !== measuredHeight) setHeight(measuredHeight)
setHeight(measuredHeight)
Copy link
Contributor Author

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])
Copy link
Contributor Author

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

}, [wasRenderedOnClientAtLeastOnce])
return wasRenderedOnClientAtLeastOnce ? height : null
}

Expand All @@ -57,10 +57,10 @@ function useWasRenderedOnClientAtLeastOnce() {
] = useState(false)

useEffect(() => {
if (isClient() && !wasRenderedOnClientAtLeastOnce) {
if (isClient()) {
setWasRenderedOnClientAtLeastOnce(true)
}
}, [wasRenderedOnClientAtLeastOnce])
Comment on lines 59 to -63
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

}, [])
return wasRenderedOnClientAtLeastOnce
}

Expand Down