0Pricing
React Academy · Lesson

Subscribing to Browser APIs

Build hooks that subscribe to matchMedia, navigator.onLine, window history, and localStorage using useSyncExternalStore.

Subscribing to matchMedia

Browser media queries are a perfect external store. You can subscribe to a matchMedia query for dark mode or a breakpoint and re-render whenever the match state flips.

The subscribe function adds a change listener to the MediaQueryList, and getSnapshot returns its current matches boolean, giving you reactive access to responsive conditions.

A useMediaQuery Hook

Wrapping that logic into a useMediaQuery hook lets components ask whether a query matches with a single call. The hook builds a stable subscribe and getSnapshot around a given query string.

This produces a clean, reusable primitive for responsive behavior that stays consistent under concurrent rendering thanks to useSyncExternalStore.

All lessons in this course

  1. The Problem with External Store Subscriptions
  2. useSyncExternalStore API and Parameters
  3. Subscribing to Browser APIs
  4. Building a Custom Store with useSyncExternalStore
← Back to React Academy