Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor useDeviceOrientation hook #212

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 13 additions & 29 deletions src/useDeviceOrientation.ts
Original file line number Diff line number Diff line change
@@ -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
}