Skip to content

useMedia flashes wrong stateΒ #83

Description

@dreyks

defaultMatches bleeds through the initial render resulting in flashes of wrong state. replacing useEffect with useLayoutEffect would fix this but would require a workaround for server-side rendering

alternatively something like this could work

const mediaQueryList = useRef()
const getMediaQueryList = () => window.matchMedia(
  typeof query === 'string' ? query : json2mq(query)
);
let initialMatches;
if (typeof window !== 'undefined') {
  mediaQueryList.current = getMediaQueryList();
  initialMatches = mediaQueryList.current.matches;
}

initialMatches = typeof initialMatches !== 'undefined' ? initialMatches : defaultMatches;
const [matches, setMatches] = useState(initialMatches);

useEffect(
  () => {
    mediaQueryList.current = mediaQueryList.current || getMediaQueryList()
    // the rest of the method
  },
  [query]
)

what do you think?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions