Craig Grummitt – Before I forget

Discoveries in Swift and iOS development.

, , ,

SwiftUI vs React Native: Environment vs Context

·

In a previous article, SwiftUI vs React Native: State, we looked at how the two frameworks manage local state. We then followed up with a look at Binding vs Props, exploring how a parent view can share state with a child view.

But what happens when the child isn’t directly beneath the parent? What if several layers of views sit between them, and those intermediate views don’t actually need the data?

Passing values and callbacks through every level of the view hierarchy can quickly become cumbersome.

This is where SwiftUI’s @Environment and React’s Context come in.

Both provide a way to make values available to descendant views or components without having to explicitly pass them through every intermediate level.

Let’s take a look.

The problem: Passing data down the hierarchy

Imagine we’re building a shopping application.

We have a parent view containing our shopping cart, and somewhere further down the hierarchy we have a cart icon that needs to display the number of items.

We could pass the shopping cart through every intermediate view, even though most of those views don’t actually need it.

In React, this is commonly known as prop drilling. The same problem exists in SwiftUI, although the terminology is less commonly used.

We explored @Binding and props in the previous article, but those approaches can become cumbersome when data needs to travel through a large view hierarchy.

Wouldn’t it be easier if the cart could simply be accessed wherever it was needed?

That’s exactly what Environment and Context allow us to do.

SwiftUI and React Native - Environment vs Context

SwiftUI: @Environment

SwiftUI provides an environment mechanism that allows values to be made available throughout a view hierarchy.

We’ve already seen how to create an observable model using @Observable. We can combine this with @Environment to distribute the model to descendant views.

Let’s start with our shopping cart:

import Observation

@Observable
class ShoppingCart {
    var items: [Product] = []

    var itemCount: Int {
        items.count
    }

    func add(_ product: Product) {
        items.append(product)
    }
}

Rather than passing the shopping cart through every view, we can make it available in the environment.

First, we create and own the model in our parent view:

struct ContentView: View {
    @State private var cart = ShoppingCart()

    var body: some View {
        ShopView()
            .environment(cart)
    }
}

Notice the .environment(cart) modifier.

This makes our shopping cart instance available to descendant views.

Now, any view further down the hierarchy can access it using @Environment:

struct CartIcon: View {
    @Environment(ShoppingCart.self)
    private var cart

    var body: some View {
        Text("Cart: \(cart.itemCount)")
    }
}

That’s all there is to it!

We don’t need to pass the shopping cart through intermediate views, and we don’t need to worry about which views sit between ContentView and CartIcon.

The same instance is available wherever it’s needed.

One important distinction is that @Environment doesn’t itself make the model observable. That’s the job of @Observable. Environment provides access to the model, while SwiftUI’s Observation framework tracks which properties a view reads and updates the relevant views when those properties change.

SwiftUI also uses the environment for many built-in values, such as colour scheme, locale and accessibility settings.

So it’s not just a mechanism for sharing application data; it’s also a way of distributing configuration and dependencies throughout the view hierarchy.

React Native: Context and useContext

React has a similar mechanism called Context.

We can create a context specifically for our shopping cart:

import {
  createContext,
  useContext,
  useState
} from 'react';

const CartContext = createContext(null);

We then create a provider component that owns the state and makes it available to its descendants.

function CartProvider({ children }) {
  const [items, setItems] = useState([]);

  const add = (product) => {
    setItems(current => [...current, product]);
  };

  const value = { items, add };

  return (
    <CartContext.Provider value={value}>
      {children}
    </CartContext.Provider>
  );
}

We wrap the part of our application that needs access to the shopping cart:

function App() {
  return (
    <CartProvider>
      <ShopScreen />
    </CartProvider>
  );
}

Now any descendant component can access the shopping cart using useContext:

function CartIcon() {
  const cart = useContext(CartContext);

  return (
    <Text>Cart: {cart.items.length}</Text>
  );
}

Just like SwiftUI, we don’t need to pass the cart through every intermediate component.

The provider makes the value available to all descendant components that consume that context.

We can also have multiple contexts for different purposes, such as user authentication, application settings or shopping cart data.

So, are @Environment and Context the same thing?

They certainly have a lot in common.

Both allow us to distribute values through a hierarchy without explicitly passing them from parent to child at every level.

However, there are some differences worth exploring.

1. How values are provided

In SwiftUI, we can inject values directly into the environment using the .environment() modifier.

In React, we create a Context object and use its Provider to make a value available to descendants.

There is also a difference in how we access them:

  • SwiftUI uses @Environment.
  • React uses useContext.

2. What can be distributed?

SwiftUI’s environment is used for both application dependencies and system configuration.

For example, we can access the current colour scheme with:

@Environment(\.colorScheme)
var colorScheme

React Context can distribute virtually any JavaScript value, including objects, functions, strings and numbers.

We could create separate contexts for authentication, theme settings and application data.

Both mechanisms are flexible, but SwiftUI has a particularly strong integration with the framework’s built-in environment values.

3. How changes are handled

This is perhaps the most interesting difference.

In SwiftUI, when we inject an @Observable model into the environment, SwiftUI can track which properties a view actually reads.

For example, if our cart icon only reads cart.itemCount, changes to unrelated properties don’t necessarily require that view to update.

React Context works differently.

When a provider’s value changes, components consuming that context will generally re-render. React compares the previous and new context values using Object.is.

This means a component that only uses cart.items.length can still re-render when another part of the context value changes.

There are ways to optimise this in React, such as splitting contexts, using memoisation or using external state management libraries with more granular subscriptions.

But the underlying mechanisms are different.

SwiftUI’s Observation framework tracks property access, whereas React Context distributes values and notifies consumers when the context value changes.

Wait, isn’t this just a singleton?

Developers who have been around for a while might recognise something familiar here. Before Environment and Context became common patterns, singletons were frequently used to make shared data and services accessible throughout an application.

There are similarities, but an important distinction: a singleton provides globally accessible access to a single instance, whereas Environment and Context allow dependencies to be distributed within a particular hierarchy.

You could even provide different instances to different parts of your application, something that isn’t as straightforward with a traditional singleton.

In some ways, they’re solving the same problem, but with more flexibility and better control over scope.

A quick comparison

ConceptSwiftUIReact Native
Create shared dependencyObservable model / Environment valuecreateContext()
Provide value.environment()Context.Provider
Access value@EnvironmentuseContext
ScopeView hierarchyComponent hierarchy
Built-in configurationEnvironment valuesContext values
Change trackingObservation framework, where applicableContext value comparison

Different approaches, similar goals

Once again, we’re seeing two frameworks solving a similar problem using different mechanisms.

SwiftUI combines its environment system with the Observation framework to provide a convenient way of distributing and observing shared models.

React uses Context to distribute values throughout a component hierarchy, with state management handled separately through hooks or external libraries.

Neither approach means that all application state should be made globally accessible. Keeping state as close as possible to where it’s needed is still a good design principle.

The real benefit of Environment and Context is that they allow us to avoid unnecessary data passing when information genuinely needs to be accessible across multiple levels of an application.

And while the concepts are similar, the differences in how the frameworks handle observation and updates are worth understanding.


What’s next?

So far, we’ve looked at local state, bindings and shared values. But there’s another interesting question:

How do we manage and observe application state as our applications become more complex?

SwiftUI has Apple’s Observation framework, while React has a whole ecosystem of state management libraries such as Zustand and Redux.

In the next article, we’ll explore those approaches and look at how the two frameworks handle state management beyond the basics.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *