xref: /MusicFree/src/hooks/useOrientation.ts (revision ab5f994a52bee1ac7c89f2ccf9b6ca60d362890a)
1import {atom, useAtomValue, useSetAtom} from 'jotai';
2import {useEffect} from 'react';
3import {Dimensions} from 'react-native';
4
5const orientationAtom = atom<'vertical' | 'horizontal'>('vertical');
6
7export function useListenOrientationChange() {
8    const setOrientationAtom = useSetAtom(orientationAtom);
9    useEffect(() => {
10        const windowSize = Dimensions.get('window');
11        const {width, height} = windowSize;
12        if (width < height) {
13            setOrientationAtom('vertical');
14        } else {
15            setOrientationAtom('horizontal');
16        }
17        const subscription = Dimensions.addEventListener('change', e => {
18            if (e.window.width < e.window.height) {
19                setOrientationAtom('vertical');
20            } else {
21                setOrientationAtom('horizontal');
22            }
23        });
24
25        return () => {
26            subscription?.remove();
27        };
28    }, []);
29}
30
31export default function useOrientation() {
32    return useAtomValue(orientationAtom);
33}
34