Skip to content

Commit

Permalink
fix: support useMedia usage server-side
Browse files Browse the repository at this point in the history
  • Loading branch information
streamich authored Jul 16, 2019
2 parents 446806c + d2de3d8 commit 50a5160
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 3 deletions.
9 changes: 8 additions & 1 deletion docs/useMedia.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

React sensor hook that tracks state of a CSS media query.


## Usage

```jsx
Expand All @@ -18,3 +17,11 @@ const Demo = () => {
);
};
```

## Reference

```ts
useMedia(query: string, defaultState: boolean = false): boolean;
```

The `defaultState` parameter is only used as a fallback for server side rendering.
5 changes: 3 additions & 2 deletions src/useMedia.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { useEffect, useState } from 'react';
import { isClient } from './util';

const useMedia = (query: string) => {
const [state, setState] = useState(() => window.matchMedia(query).matches);
const useMedia = (query: string, defaultState: boolean = false) => {
const [state, setState] = useState(isClient ? () => window.matchMedia(query).matches : defaultState);

useEffect(() => {
let mounted = true;
Expand Down

0 comments on commit 50a5160

Please sign in to comment.