State and data flow

Share JavaScript objects across views like ObservableObject and @Observable in SwiftUI.

JavaScript classes can behave like SwiftUI's ObservableObject and @Observable. You can share one object across views, read it anywhere below the view that supplied it, and bind controls to its properties with $.

For local state, useBinding gives a component its own binding, as @State does.

ObservableObject

Every change re-renders all components that read the object, like ObservableObject in Swift.

import {
  compose, NavigationStack, ObservableObject, Text, TextField, VStack,
  useEnvironmentObject, useStateObject,
} from 'swiftui-react-native';

class Session extends ObservableObject {
  name = 'Ada';
  favorites: string[] = [];

  addFavorite(language: string) {
    this.favorites.push(language);
  }
}

export function App() {
  // @StateObject var session = Session()
  const session = useStateObject(() => new Session());
  return (
    // .environmentObject(session)
    <NavigationStack modifiers={compose().environmentObject(session)}>
      <Profile />
    </NavigationStack>
  );
}

function Profile() {
  // @EnvironmentObject var session: Session
  const session = useEnvironmentObject(Session);
  return (
    <VStack>
      <Text>{`Hello, ${session.name}`}</Text>
      {/* $session.name */}
      <TextField text={session.$name}>Name</TextField>
    </VStack>
  );
}

Observable

A component re-renders only when a property it read changes, like @Observable in Swift.

import { useState } from 'react';
import {
  Button, compose, NavigationStack, Observable, Text, TextField, VStack,
  useBindable, useEnvironment, withAnimation,
} from 'swiftui-react-native';

class Book extends Observable {
  title = 'Dune';
}

class Library extends Observable {
  name = 'City Library';
  books: Book[] = [new Book()];

  get count() {
    return this.books.length;
  }
}

export function App() {
  // @State private var library = Library()
  const [library] = useState(() => new Library());
  return (
    // .environment(library)
    <NavigationStack modifiers={compose().environment(library)}>
      <VStack>
        <LibraryName />
        <BookCount />
      </VStack>
    </NavigationStack>
  );
}

function LibraryName() {
  // @Environment(Library.self) private var library
  const library = useEnvironment(Library);
  // Re-renders when name changes, not when books do.
  return <Text>{library.name}</Text>;
}

function BookCount() {
  const library = useEnvironment(Library);
  return (
    <VStack>
      <Text>{`${library.count} books`}</Text>
      {library.books.map((book, index) => (
        <BookEditor key={index} book={book} />
      ))}
      <Button onPress={() => withAnimation(() => library.books.push(new Book()))}>
        Add book
      </Button>
    </VStack>
  );
}

function BookEditor({ book }: { book: Book }) {
  // @Bindable var book: Book
  const bindable = useBindable(book);
  return <TextField text={bindable.$title}>Title</TextField>;
}

Focus

A view can publish an object while it has focus, and any component can read it.

function NoteEditor({ note }: { note: Note }) {
  const bindable = useBindable(note);
  return (
    // .focusedValue(note)
    <TextField text={bindable.$title} modifiers={compose().focusedValue(note)}>
      Title
    </TextField>
  );
}

function FormattingBar() {
  // @FocusedValue(Note.self) private var note
  const note = useFocusedValue(Note);
  return <Text>{note ? `Editing ${note.title}` : 'Nothing selected'}</Text>;
}

focusedObject and focusedSceneObject publish an ObservableObject, read with useFocusedObject. focusedValue and focusedSceneValue publish an Observable, read with useFocusedValue.

Quick reference

SwiftUIswiftui-react-native
class X: ObservableObjectclass X extends ObservableObject
@StateObject var x = X()useStateObject(() => new X())
@ObservedObject var xuseObservedObject(x)
.environmentObject(x) / @EnvironmentObjectcompose().environmentObject(x) / useEnvironmentObject(X)
@Observable class Xclass X extends Observable
@State var x = X()useState(() => new X()) + useObservable(x)
@Bindable var xuseBindable(x)
.environment(x) / @Environment(X.self)compose().environment(x) / useEnvironment(X)
@Environment(X?.self)useEnvironment(X, { optional: true })
$x.namex.$name
.focusedObject / .focusedSceneObject + @FocusedObjectsame modifiers + useFocusedObject(X)
.focusedValue / .focusedSceneValue + @FocusedValue(X.self)same modifiers + useFocusedValue(X)
withObservationTrackingwithObservationTracking(apply, { onChange })

What counts as a change

  • Properties: assigning a property, from anywhere, including class methods and withAnimation.
  • Values inside a property: arrays and plain objects, Map (set, delete, clear), Set (add, delete, clear) and Date (its set methods).
  • Same values: writing a value equal to the current one is not a change.

With Observable, a component depends on the properties it reads while it renders. That includes getters, nested Observable objects, and closures SwiftUI calls while it renders, such as List rows and GeometryReader. Reads in event handlers don't count, as in a SwiftUI action.

Reaching descendants

The object reaches every component below the view that supplied it, including sheets, toolbar items, navigation destinations and render closures.

  • Nearest wins: the nearest ancestor that supplied the type wins.
  • One view, several modifiers: the first modifier is the closest to the view, so its object wins, as in SwiftUI.
  • Subclasses: a lookup by a base class also finds a subclass instance.
  • Missing objects: a missing object throws SwiftUI's own error message. useEnvironment(X, { optional: true }) gives null instead.

Limitations

  • Swift code reading these objects: they're JavaScript objects.
  • Core Data: FetchRequest and SectionedFetchRequest.
  • App and scene level: UIApplicationDelegateAdaptor, Scene.environment and Scene.environmentObject.
  • Deeper bindings: nested bindings into plain structs ($x.profile.city) and per-element list bindings (ForEach($items)).

Good to know

  • Identity: useObservable, useBindable and useEnvironment return the component's own view of the object. It's the same data, but a different reference, so compare objects from different components by id, not with ===.
  • Memoized children: a child wrapped in React.memo that reads an object it was passed should call one of the hooks itself.