Skip to content

[BUG] useMediaQuery SSR case #701

@quantizor

Description

@quantizor

Describe the bug

I want the server to render in mobile mode for SSR and then, after mount, I want to run the actual media query and have the UI update without a hydration mismatch. It doesn't seem to be possible to arrive at this behavior with the current hook setup.

To Reproduce

const isMobile = useMediaQuery("(max-width: 768px)", {
  defaultValue: true,
  initializeWithValue: false,
});

Expected behavior

  1. SSR occurs, isMobile is set to true due to defaultValue
  2. Page loads, isMobile remains true
  3. Initial mount completes, hook re-evaluates and determines that the page is >768px so isMobile is updated to false, UI updates to the correct end state

Additional context

I've tried various combinations of defaultValue and initializeWithValue, none seem to arrive at the desired behavior. It's very important that the final evaluation happens after mount such as to not cause a rehydration warning/error.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions