isRetina
Checks if the device has a high pixel density (Retina or HiDPI screen).
1/**
2 * Checks if the device has a high pixel density (Retina or HiDPI screen).
3 *
4 * @returns True if the device is retina, false otherwise.
5 */
6export function isRetina(): boolean {
7 if (typeof window === 'undefined') return false;
8 return window.devicePixelRatio > 1;
9}
Simple and Direct Logic
Relies on a single property (
window.devicePixelRatio
) for a clear, fast determination of screen density.Minimal Resource Usage
Performs no DOM operations or media queries - lightweight and efficient in execution.
SSR-Safe Implementation
Guards against undefined
window
to avoid runtime errors in server-rendered or non-browser environments.
Tests | Examples
1const originalDevicePixelRatio = window.devicePixelRatio;
2
3afterEach(() => {
4 Object.defineProperty(window, 'devicePixelRatio', {
5 value: originalDevicePixelRatio,
6 configurable: true,
7 });
8});
9
10test('returns true if devicePixelRatio > 1', () => {
11 Object.defineProperty(window, 'devicePixelRatio', {
12 value: 2,
13 configurable: true,
14 });
15 expect(isRetina()).toBe(true);
16});
17
18test('returns false if devicePixelRatio <= 1', () => {
19 Object.defineProperty(window, 'devicePixelRatio', {
20 value: 1,
21 configurable: true,
22 });
23 expect(isRetina()).toBe(false);
24});
25
26test('returns false in non-browser environments', () => {
27 const originalWindow = globalThis.window;
28 // @ts-expect-error
29 delete globalThis.window;
30 expect(isRetina()).toBe(false);
31 globalThis.window = originalWindow;
32});
Common Use Cases
Serving High-Resolution Images
Load
@2x
or@3x
image assets for Retina and HiDPI screens to improve visual clarity.Adaptive Styling or Scaling
Adjust CSS styling, canvas rendering, or SVG details based on pixel density.
Conditional Asset Delivery
Select optimized resources (e.g., fonts, icons) tailored for high-DPI vs. standard displays.
UI Testing or Analytics
Detect display density as part of feature usage tracking or automated UI environment profiling.