Skip to content

Commit

Permalink
fix(breakpoints): races in useViewportWidth
Browse files Browse the repository at this point in the history
The main fix here is changing the initial state from null to
window.innerWidth, so that there isn't a useless transition from (for
example) `useDown('md') = true` to `useDown('md') = false` when the
application loads. Depending on the application, the rerendering penalty
can be heavy.

While we're here, notice that we can make a couple related changes:
First, since the initial state is set properly, we don't need a layout
effect, instead we can use a normal effect. Second, swap the order of
listener and setWidth to avoid the tiny race between them.
  • Loading branch information
agriffis committed Jul 19, 2020
1 parent 951a2b8 commit c5e9e05
Showing 1 changed file with 5 additions and 4 deletions.
9 changes: 5 additions & 4 deletions packages/core/src/breakpoints.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,16 +31,17 @@ function useThemeMaxValue(theme, key) {
}

export function useViewportWidth() {
const [width, setWidth] = React.useState(null)

React.useLayoutEffect(() => {
setWidth(window.innerWidth)
const [width, setWidth] = React.useState(window?.innerWidth)

React.useEffect(() => {
function handleResize() {
setWidth(window.innerWidth)
}

// Add the listener, then setWidth to avoid race.
window.addEventListener('resize', handleResize)
setWidth(window.innerWidth)

return () => window.removeEventListener('resize', handleResize)
}, [])

Expand Down

0 comments on commit c5e9e05

Please sign in to comment.