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

Return media query value from useMedia on initial render #78

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 23 additions & 12 deletions src/useMedia.tsx
Original file line number Diff line number Diff line change
@@ -1,37 +1,48 @@
import { useState, useEffect } from 'react';
import React from 'react';
import json2mq from 'json2mq';

export function useMedia(
query: string | { [key: string]: any },
defaultMatches = true
defaultMatches: boolean = true
) {
const [matches, setMatches] = useState(defaultMatches);
const mediaQueryList = React.useRef<MediaQueryList | undefined>(undefined);

useEffect(
const [matches, setMatches] = React.useState(() => {
if (typeof window !== 'object') {
return defaultMatches;
}

mediaQueryList.current = window.matchMedia(
typeof query === 'string' ? query : json2mq(query)
);

return !!mediaQueryList.current.matches;
});

React.useEffect(
() => {
const mediaQueryList = window.matchMedia(
typeof query === 'string' ? query : json2mq(query)
);
let active = true;
// mediaQueryList.current will only be undefined on the server
const currentMediaQueryList = mediaQueryList.current!;

let active = true;
const listener = () => {
if (!active) {
return;
}

if (mediaQueryList.matches) {
if (currentMediaQueryList.matches) {
setMatches(true);
} else {
setMatches(false);
}
};

mediaQueryList.addListener(listener);
setMatches(mediaQueryList.matches);
currentMediaQueryList.addListener(listener);
setMatches(matches);

return () => {
active = false;
mediaQueryList.removeListener(listener);
currentMediaQueryList.removeListener(listener);
};
},
[query]
Expand Down