-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathuseDeviceOrientation.hook.ts
More file actions
40 lines (33 loc) · 1.07 KB
/
useDeviceOrientation.hook.ts
File metadata and controls
40 lines (33 loc) · 1.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import React, { useRef } from 'react';
import RNOrientationDirector from '../RNOrientationDirector';
import type { OrientationEvent } from '../types/OrientationEvent.interface';
import { Orientation } from '../types/Orientation.enum';
/**
* Hook that returns the current device orientation.
* It listens for orientation changes and updates the state accordingly.
*/
const useDeviceOrientation = () => {
const initialRender = useRef(false);
const [orientation, setOrientation] = React.useState<Orientation>(
Orientation.unknown
);
React.useEffect(() => {
if (initialRender.current) {
return;
}
initialRender.current = true;
RNOrientationDirector.getDeviceOrientation().then(setOrientation);
}, []);
React.useEffect(() => {
const onChange = (event: OrientationEvent) => {
setOrientation(event.orientation);
};
const subscription =
RNOrientationDirector.listenForDeviceOrientationChanges(onChange);
return () => {
subscription.remove();
};
}, []);
return orientation;
};
export default useDeviceOrientation;