Skip to content

Commit

Permalink
fix(breakpoints): races in useViewportWidth (#114)
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 27, 2020
1 parent 997273f commit fc70500
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(typeof window === 'undefined' ? null : 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 fc70500

Please sign in to comment.