easyReact Native#27

Dynamic Styles with useWindowDimensions

Prompt

Use useWindowDimensions to render a responsive layout. Show "Landscape" when width > height, otherwise show "Portrait".

Solution

const { width, height } = useWindowDimensions()
const isLandscape = width > height
return <Text style={{ fontSize: 24 }}>{isLandscape ? 'Landscape' : 'Portrait'}</Text>
Mentor's take

The hook exists because screen size is state, not a constant — rotation, foldables, split-screen multitasking, and resizable windows all change it mid-session. useWindowDimensions subscribes the component to those changes: rotate the device and the component re-renders with fresh numbers, no listener plumbing. Its predecessor, Dimensions.get('window'), is a one-time read — correct at the moment you call it, silently stale afterward.

That distinction produces the classic bug this question fishes for: Dimensions.get('window').width inside StyleSheet.create at module scope. It's evaluated once, at import time — rotate, and the layout is permanently wrong until app restart. It looks responsive and isn't, which is what makes it dangerous in review. Anything derived from dimensions must be computed in render, where the hook keeps it live.

Deriving orientation as width > height rather than from a separate orientation API is the right instinct — one source of truth, no second subscription to keep in sync. Also worth a sentence: window excludes system decorations on Android (vs screen), and dimension-based breakpoints compose with useSafeAreaInsets for real device-adaptive layout.

Red flag: dimensions captured in module scope or StyleSheet.create. If layout math lives outside render, rotation breaks it — the interviewer wants to hear "computed at render time, subscribed via the hook."

Say it: "Screen size is state — useWindowDimensions subscribes me to it, whereas Dimensions.get is a stale one-time read, so any dimension math belongs in render, never in module-scope StyleSheets."