14 / 14

Implement useMediaQuery hook.

javascript
Difficulty: 6/10
Topics: custom hooks, window.matchMedia, SSR

Scenario Questions

0-2 years experience
  1. 1

    How would you write a simple useMediaQuery hook that returns true when the viewport matches a given CSS media query string?

  2. 2

    If you call your hook with '(max-width: 600px)' and then resize the window, what steps does your hook need to take to update the component?

2-5 years experience
  1. 1

    We have a component that shows a mobile navigation drawer only on screens smaller than 768px. It sometimes doesn't hide when the window is resized larger. Walk me through how you'd debug the useMediaQuery implementation.

  2. 2

    Explain why you might want to debounce the media query listener in your hook, and show how you'd add that.

5-8 years experience
  1. 1

    In a large application, many components use useMediaQuery. What strategies would you use to avoid creating a separate matchMedia listener for each hook instance?

  2. 2

    How would you adapt your useMediaQuery hook to work correctly with server-side rendering and avoid hydration mismatches?

8+ years experience
  1. 1

    Our design system team wants to expose a shared media query utility across multiple micro‑frontends. What architectural considerations would you raise when deciding whether to ship useMediaQuery as a library versus a built‑in framework feature?

  2. 2

    If we need to support legacy browsers that lack window.matchMedia, how would you design a fallback strategy that keeps the hook's API stable across the organization?

Follow-up Questions

  • What would happen if you omitted the cleanup function?
  • How does your hook behave during the initial render on the server?
  • Can you think of any performance implications of many components using this hook?