React Native's Dimensions API: The Manual Approach
React Native's `Dimensions` API is a low-level way to get a one-time snapshot of screen or window sizes. Use it outside React components or when you need to subscribe to changes manually. The footgun is caching its value, as it won't update on rotation.
WHY IT EXISTS To create responsive layouts, applications need to know the size of the device's screen and the available application window. The Dimensions API was the original mechanism in React Native to provide this crucial geometry information programmatically.
THE MENTAL MODEL Think of Dimensions.get() as taking a single photograph of the screen's size. The photo is accurate at the moment it's taken, but it doesn't change if the real world does (like when a user rotates their phone). To see changes, you must either take a new photo (get() again) or set up a live video feed (addEventListener). The modern useWindowDimensions hook is that live feed, but built specifically for React components.
HOW IT WORKS The API has two main functions. First, Dimensions.get(dim) synchronously returns an object with the current width and height. The dim parameter can be 'window' (the visible app area, excluding things like the status bar on Android) or 'screen' (the full physical display). Second, Dimensions.addEventListener('change', handler) lets you subscribe to dimension updates, such as from device rotation or folding. The handler function receives the new window and screen sizes.
WHEN TO USE IT Use the Dimensions API primarily outside of React components, for example, in non-UI utility functions or services that need screen size information but don't have a render lifecycle. It's also the fallback for older class-based components where you can manually manage listeners in lifecycle methods like componentDidMount and componentWillUnmount.
WHEN NOT TO USE IT Avoid Dimensions inside modern React functional components. The useWindowDimensions hook is the preferred API. It automatically subscribes to updates and triggers a re-render with the new values, which is simpler, more declarative, and less error-prone than manually managing listeners with the Dimensions API.
ONE CANONICAL EXAMPLE To get the initial window width, you would call const windowWidth = Dimensions.get('window').width;. The common mistake is storing this in a constant, as it will become stale. A more robust, but manual, approach requires setting up a listener: const subscription = Dimensions.addEventListener('change', ({ window }) => { /* update state with window.width */ });. You must also remember to call subscription.remove() to prevent memory leaks when the component unmounts.
Read the original → reactnative.dev
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.