From 8c3d1211213bbc2451e5fa0287a3460d726b9240 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Linus=20Unneb=C3=A4ck?= Date: Wed, 4 Nov 2020 15:22:47 +0100 Subject: [PATCH] Refactor useDeviceOrientation hook --- src/useDeviceOrientation.ts | 42 ++++++++++++------------------------- 1 file changed, 13 insertions(+), 29 deletions(-) diff --git a/src/useDeviceOrientation.ts b/src/useDeviceOrientation.ts index 403bdc4e..c14e581a 100644 --- a/src/useDeviceOrientation.ts +++ b/src/useDeviceOrientation.ts @@ -1,43 +1,27 @@ import {useEffect, useState, useCallback} from 'react' import {Dimensions, ScaledSize} from 'react-native' -const screen = Dimensions.get('screen') +interface DeviceOrientation { + portrait: boolean + landscape: boolean +} -export function useDeviceOrientation() { - const isOrientationPortrait = ({ - width, - height, - }: { - width: number - height: number - }) => height >= width - const isOrientationLandscape = ({ - width, - height, - }: { - width: number - height: number - }) => width >= height +function calculateDeviceOrientation(screen: ScaledSize): DeviceOrientation { + return { portrait: screen.height >= screen.width, landscape: screen.width >= screen.height } +} - const [orientation, setOrientation] = useState({ - portrait: isOrientationPortrait(screen), - landscape: isOrientationLandscape(screen), - }) +export function useDeviceOrientation(): DeviceOrientation { + const [orientation, setOrientation] = useState(calculateDeviceOrientation(Dimensions.get('screen'))) - const onChange = useCallback(({screen: scr}: {screen: ScaledSize}) => { - setOrientation({ - portrait: isOrientationPortrait(scr), - landscape: isOrientationLandscape(scr), - }) + const onChange = useCallback(({screen}: {screen: ScaledSize}) => { + setOrientation(calculateDeviceOrientation(screen)) }, []) useEffect(() => { Dimensions.addEventListener('change', onChange) - return () => { - Dimensions.removeEventListener('change', onChange) - } - }, [orientation.portrait, orientation.landscape, onChange]) + return () => Dimensions.removeEventListener('change', onChange) + }, [onChange]) return orientation }