DOM
useScreen
Tracks window.screen, refreshing it on every resize.
Demo
live · imported from hookli
- width
- —
- height
- —
- availWidth
- —
- availHeight
- —
- colorDepth
- —
- orientation
- —
Mirrors the physical screen, not the viewport — the values stay put when you resize the window but track a move between displays.
import { useScreen } from "hookli";
export function Demo() {
const screen = useScreen();
return <p>Screen: {screen ? `${screen.width}×${screen.height}` : "…"}</p>;
}Usage
import { useScreen } from "hookli";
export function Demo() {
const screen = useScreen();
return <p>Screen: {screen ? `${screen.width}×${screen.height}` : "…"}</p>;
}API
useScreen(options?: UseScreenOptions): Screen | nullParameters
| Name | Type | Default | Description |
|---|---|---|---|
| options | UseScreenOptions | {} | Hydration behaviour. Optional. |
Returns
| Name | Type | Description |
|---|---|---|
| screen | Screen | null | The current window.screen (width, height, availWidth, colorDepth, orientation…), refreshed on every resize. null on the server and until hydration. |
UseScreenOptions
Configures mount behaviour.
| Name | Type | Description |
|---|---|---|
| initializeWithValue | boolean | Read the real screen synchronously on mount. Set false to start as null and populate after hydration. |
Hook
The implementation, straight from hookli. Copy it, or install the package.
import { useState } from "react";
import { useEventListener } from "../use-event-listener/use-event-listener";
import { useIsomorphicLayoutEffect } from "../use-isomorphic-layout-effect/use-isomorphic-layout-effect";
interface UseScreenOptions {
initializeWithValue?: boolean;
}
const IS_SERVER = typeof window === "undefined";
export function useScreen(options: UseScreenOptions = {}): Screen | null {
const { initializeWithValue = true } = options;
const readScreen = (): Screen | null => {
if (IS_SERVER) return null;
return window.screen;
};
const [screen, setScreen] = useState<Screen | null>(() => {
if (initializeWithValue) return readScreen();
return null;
});
const handleSize = () => {
setScreen(readScreen());
};
useEventListener("resize", handleSize);
useIsomorphicLayoutEffect(() => {
handleSize();
}, []);
return screen;
}