BrowserBeginnerSSR-safehooks/browser/useDeviceOrientation.ts

useDeviceOrientation

Device orientation events.

Import

TypeScript
import { useDeviceOrientation } from '@/hooks';

API

Signature

useDeviceOrientation(options?) → orientation

When to use

Use useDeviceOrientation instead of re-implementing the same pattern in multiple components.

SSR / Next.js

Returns defaults on the server; hydrates on the client.

Live playground

Edit the example and see it run against the real @/hooks package in this app.

Live playgroundEdit · run with real @/hooks · useDeviceOrientation
Editor
function Tilt() {
  const { alpha, beta, gamma, supported } = useDeviceOrientation();
  if (!supported) return <p>Not supported</p>;
  return <p>{alpha} / {beta} / {gamma}</p>;
}
Preview

Implementation source

Full library source for useDeviceOrientation — copy into your project when you are not installing a package yet.

hooks/browser/useDeviceOrientation.ts
import { useEffect, useState } from 'react';
import { isBrowser } from '../utility/isBrowser';

export interface DeviceOrientationState {
  absolute: boolean;
  alpha: number | null;
  beta: number | null;
  gamma: number | null;
  supported: boolean;
}

/** Device orientation events when supported. */
export function useDeviceOrientation(
  options: { enabled?: boolean } = {},
): DeviceOrientationState {
  const { enabled = true } = options;
  const [state, setState] = useState<DeviceOrientationState>({
    absolute: false,
    alpha: null,
    beta: null,
    gamma: null,
    supported: isBrowser() && 'DeviceOrientationEvent' in window,
  });

  useEffect(() => {
    if (!isBrowser() || !enabled || !('DeviceOrientationEvent' in window)) {
      return;
    }

    const handler = (event: DeviceOrientationEvent) => {
      setState({
        absolute: event.absolute,
        alpha: event.alpha,
        beta: event.beta,
        gamma: event.gamma,
        supported: true,
      });
    };

    window.addEventListener('deviceorientation', handler);
    return () => window.removeEventListener('deviceorientation', handler);
  }, [enabled]);

  return state;
}

Copy-paste example

useDeviceOrientation.example.tsx
'use client';

import { useDeviceOrientation } from '@/hooks';

export function Tilt() {
  const { alpha, beta, gamma, supported } = useDeviceOrientation();
  if (!supported) return <p>Not supported</p>;
  return <p>{alpha} / {beta} / {gamma}</p>;
}

Production checklist

  • Called only from Client Components or other custom hooks
  • Type parameters filled in (e.g. useFetch<User[]>)
  • Tip: Values are safe during SSR (defaults). Gate layout-dependent UI with useMounted when needed.
  • Source of truth: open hooks/browser/useDeviceOrientation.ts for implementation details