useDeviceMotion
Provides device motion data via snapshot and watch().
Usage
import { useDeviceMotion } from "@siberiacancode/reactuse";
const motion = useDeviceMotion();
const value = motion.watch();Example
const motion = useDeviceMotion();
const value = motion.watch();
return (
<div>
{Math.round(value.accelerationIncludingGravity.x ?? 0)} /{" "}
{Math.round(value.accelerationIncludingGravity.y ?? 0)}
</div>
);enabled:
const motion = useDeviceMotion({ enabled: false });onChange:
const motion = useDeviceMotion({ onChange: (event) => console.log(event) });Notes
- Hook uses the DeviceMotionEvent API.
- By default device motion updates
snapshotandonChangewithout forcing a re-render. To render live motion data in JSX, subscribe viawatch(): call it once per render, for exampleconst value = motion.watch(), then the component will re-render on motion updates.
Type Declarations
export interface UseDeviceMotionReturn {
snapshot: UseDeviceMotionValue;
watch: () => UseDeviceMotionValue;
}
export interface UseDeviceMotionValue {
acceleration: DeviceMotionEventAcceleration;
accelerationIncludingGravity: DeviceMotionEventAcceleration;
interval: DeviceMotionEvent["interval"];
rotationRate: DeviceMotionEventRotationRate;
}
export interface UseDeviceMotionOptions {
enabled?: boolean;
onChange?: (event: DeviceMotionEvent) => void;
}
export interface UseDeviceMotion {
(callback?: (event: DeviceMotionEvent) => void): UseDeviceMotionReturn;
(options?: UseDeviceMotionOptions): UseDeviceMotionReturn;
}
export declare const useDeviceMotion: UseDeviceMotion;