A Practical React Native Problem Solved with the Context API

Context is a go for React Native

Excitement is in the air these past few weeks. The React community hit huge milestones with the release of React 16.3. The React Native community was quick to respond and now fully supports the 16.3 version with React Native 0.55.

What does it mean for Native development?


Context Is a Go For Launch

Context is now a first-class API that is supported by the community. The React team describes it best:

Version 16.3 introduces a new context API that is more efficient and supports both static type checking and deep updates.

There are numerous use cases for the Context API. I will show you how it can solve some common problems in native development.

Responsive Layouts

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.
  • 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.


I hope this post demonstrated a concrete application of the context API. It was trivial to get running and quickly reduced code duplication in my app. You can find these components on NPM and the source on GitHub. I would love to hear your thoughts on the context API and React in general. Reach out to me in the comments or Twitter.