1
mirror of https://github.com/jakejarvis/jarv.is.git synced 2025-07-03 17:46:39 -04:00

move useMedia hook here but without SSR warning

This commit is contained in:
2022-07-24 22:41:02 -04:00
parent ac9a5dfcff
commit 37feb305ff
8 changed files with 201 additions and 131 deletions

View File

@ -0,0 +1,13 @@
import { useRef } from "react";
export const useFirstMountState = (): boolean => {
const isFirstMount = useRef(true);
if (isFirstMount.current) {
isFirstMount.current = false;
return true;
}
return isFirstMount.current;
};

41
hooks/use-media.ts Normal file
View File

@ -0,0 +1,41 @@
// https://github.com/streamich/react-use/blob/e53ca94a0b1f20270b0f75dc2ca1fecf1e119dde/src/useMedia.ts
import { useEffect, useState } from "react";
const getInitialState = (query: string, defaultState?: boolean): boolean => {
if (defaultState !== undefined) {
return defaultState;
}
if (typeof window !== "undefined") {
return window.matchMedia(query).matches;
}
return false;
};
export const useMedia = (query: string, defaultState?: boolean): boolean => {
const [state, setState] = useState(getInitialState(query, defaultState));
useEffect(() => {
let mounted = true;
const mql = window.matchMedia(query);
const onChange = () => {
if (!mounted) {
return;
}
setState(!!mql.matches);
};
// TODO: switch to more modern `addEventListener()`
mql.addListener(onChange);
setState(mql.matches);
return () => {
mounted = false;
mql.removeListener(onChange);
};
}, [query]);
return state;
};

View File

@ -0,0 +1,13 @@
import { useEffect } from "react";
import { useFirstMountState } from "./use-first-mount-state";
// identical to `useEffect()` but ignores the first invocation
export const useUpdateEffect: typeof useEffect = (effect, deps) => {
const isFirstMount = useFirstMountState();
useEffect(() => {
if (!isFirstMount) {
return effect();
}
}, deps); // eslint-disable-line react-hooks/exhaustive-deps
};