Dimension API

React Native uses Yoga to provide a responsive language for flexing components. For me, this has covered the vast majority of my use cases. However, there are times where you need to know the dimensions of the device. Anyone experienced in React would expect that there would be components to fetch device dimensions. The Dimensions API provides the following high-level functionality:

Getting current window and screen dimensions.

Event-driven updates to respond to dimension changes.

Functions are so 2016. Let’s make some components!

Dimensions as Context

We can think of device dimensions as context for application components. Thinking this way gives us the following API for this context:

Dimension Provider: Manages the dimension event subscription and current device size context.

Manages the dimension event subscription and current device size context. Screen/Window Consumers: Allow components to consume the current device window and screen width and height.

How this would look in practice:

Context Components

How? React 16.3

React 16.3 made this an easy implementation with context.

Simplified Dimension Context Implementation

Notes

React.createContext The magic provided by React.

DimensionProvider: Observes device dimension changes and broadcasts that information using the context provider.

WindowConsumer: Consumes the context and provides a simplified view of the dimension data. In this case, the window width and height.

This pattern is a huge win since there is only one event listener for dimension changes. This avoids multiple re-renders and provides a single source of truth. Any component that requires this information can simply consume it. There is also the added benefit of semantics. A developer can quickly see that a component is using device dimensions.