Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Correct useMediaQuery on first render #4

Closed
jamiebuilds opened this issue Jun 27, 2024 · 1 comment
Closed

Correct useMediaQuery on first render #4

jamiebuilds opened this issue Jun 27, 2024 · 1 comment
Assignees
Labels
enhancement New feature or request

Comments

@jamiebuilds
Copy link

Using useSyncExternalStore() you can avoid adding a state and an effect in useMediaQuery() and on the first render it will be the correct value

export function useCustomMediaQuery(mediaQuery: string): boolean {
  const [subscribe, getSnapshot] = useMemo(() => {
    const mediaQueryList = globalThis.matchMedia(mediaQuery);

    function subscribe(onStoreChange: () => void) {
      mediaQueryList.addEventListener("change", onStoreChange);
      return () => mediaQueryList.removeEventListener("change", onStoreChange);
    }

    function getSnapshot() {
      return mediaQueryList.matches;
    }

    return [subscribe, getSnapshot];
  }, [mediaQuery]);

  return useSyncExternalStore(subscribe, getSnapshot);
}

export const useMediaQuery = (): MediaQueryMatches => {
  const isMobile = useCustomMediaQuery(`(max-width: ${breakpoints.tablet - 1}px)`);
	// ...

  const matches = useMemo(() => {
    return {
      isMobile,
      // ...
    };
  }, [isMobile, ...]);

  return matches;
};

But you could also adapt your current approach doing it all in one hook, you'd just need to make sure that you aren't returning a new object from getSnapshot every time it gets called.

@jake-figma jake-figma self-assigned this Jun 28, 2024
@jake-figma jake-figma added the enhancement New feature or request label Jun 28, 2024
@jake-figma
Copy link
Collaborator

Ah this is brilliant. Thanks so much.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants