Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import { MutableRefObject } from 'react';
import useIsomorphicEffect from './useIsomorphicEffect';
export type ContainerQuery =
| 'width'
| 'height'
| 'max-width'
| 'max-height'
| 'aspect-ratio'
| 'orientation';
export type ContainerOrientation = 'portrait' | 'landscape';
export default function useContainerQuery(
ref: MutableRefObject<HTMLElement | null>,
containerQuery: 'width',
value: number,
): boolean;
export default function useContainerQuery(
ref: MutableRefObject<HTMLElement | null>,
containerQuery: 'height',
value: number,
): boolean;
export default function useContainerQuery(
ref: MutableRefObject<HTMLElement | null>,
containerQuery: 'max-width',
value: number,
): boolean;
export default function useContainerQuery(
ref: MutableRefObject<HTMLElement | null>,
containerQuery: 'max-height',
value: number,
): boolean;
export default function useContainerQuery(
ref: MutableRefObject<HTMLElement | null>,
containerQuery: 'aspect-ratio',
value: number,
): boolean;
export default function useContainerQuery(
ref: MutableRefObject<HTMLElement | null>,
containerQuery: 'orientation',
value: ContainerOrientation,
): boolean;
export default function useContainerQuery(
ref: MutableRefObject<HTMLElement | null>,
containerQuery: ContainerQuery',
value: ContainerOrientation | number,
): boolean {
const [state, setState] = useState(false);
useIsomorphicEffect(() => {
setState(false);
if (ref.current != null) {
const { current } = ref;
// TODO observer callback
const observer = new ResizeObserver(callback);
observer.observe(current);
return () => {
observer.disconnect();
};
}
return undefined;
}, [ref, containerQuery, value]);
return state;
}
import { useEffect, useLayoutEffect } from 'react'
// React currently throws a warning when using useLayoutEffect on the server.
// To get around it, we can conditionally useEffect on the server (no-op) and
// useLayoutEffect in the browser. We need useLayoutEffect to ensure the store
// subscription callback always has the selector from the latest render commit
// available, otherwise a store update may happen between render and the effect,
// which may cause missed updates; we also must ensure the store subscription
// is created synchronously, otherwise a store update may occur before the
// subscription is created and an inconsistent state may be observed
const useIsomorphicEffect =
typeof window !== 'undefined' &&
typeof window.document !== 'undefined' &&
typeof window.document.createElement !== 'undefined'
? useLayoutEffect
: useEffect;
export default useIsomorphicEffect;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment