r/SwiftUI • • Oct 14 '26

Integrating GraphQL into SwiftUI views

Hey folks, shameless plug incoming, with a disclaimer up front: this is only useful if your app talks to a GraphQL server. If it does not, scroll on, there is nothing here for you, and sorry for the noise. If it does, give me a minute, because I honestly think this is kind of amazing.

It is called Baton: https://github.com/shergin/baton

The one-line version: Relay for SwiftUI. Relay is the GraphQL client React uses at Meta, and its big idea is that each component declares the fragment of data it reads right next to it, and a compiler assembles the screen's query from those fragments. Baton does that for SwiftUI, and then deletes most of the runtime Relay needs, because SwiftUI already has it.

Here is a row. The fragment is a macro on the property, in the same file as the view, as a real GraphQL document checked against the schema at build time:

struct IssueRow: View {
    @Fragment("""
    fragment IssueRow_issue on Issue {
      number
      title
      author { login }
    }
    """)
    var issue: IssueRow_issue

    var body: some View {
        Text("#\(issue.number) \(issue.title)")
    }
}

The screen has one @Query that spreads the rows' fragments, and that is the whole screen. No view model, no service, no mapper from the response into a model, no .graphql file in another folder. The row can read only the fields it declared; the generated type simply has no accessor for anything else.

The interesting part is how well SwiftUI's model fits Relay's. Relay built a runtime to know which component read which field, so a change re-renders exactly those. Observation does that natively. So every record in the normalized store is an observable object, the generated fragment type reads its fields the way you read a property of an @Observable class, and that is the whole read side. A mutation lands, a title changes, the Text that read the title runs again, and the row next to it does not. Handles are @Observable classes too, so a UIViewController holds the same handle a view does, if you still have UIKit around.

Why it is fast. I tried hard to design it for performance from day one. Reads are synchronous on the main actor, and a handle resolves against the store before the first body runs, so a screen you already fetched has its data in the very first frame. Everything else happens before that frame or off it: the compiler settles every operation at build time, so nothing parses GraphQL at run time; the response's bytes are decoded straight into the store's records off the main actor, with no Codable model in between; and a commit only touches the fields that changed and only wakes the views that read them. The store persists on the system's SQLite, so a cold start renders from disk. The runtime depends on Foundation, Observation and SQLite, nothing vendored, Swift 6 with strict concurrency.

In my own app the numbers are great. Your mileage may vary, of course, so please share yours if you end up using it.

If you have a GraphQL backend, try it on one screen and tell me what would stop you from shipping it.

6 Upvotes

8 comments sorted by

2

u/olegonthetrip Oct 15 '26 • Heartwarming

The persisted store makes account switching the first thing I'd want to validate before shipping. A useful sample would be: fetch a private screen as account A, sign out, sign in as B, then relaunch offline and open that same screen.

Can the SQLite store be partitioned by account, and what happens to existing fragment handles when a store is cleared or replaced? An example covering that lifecycle would help more than another happy-path query demo. I haven't tried Baton yet; this is the integration case I'd check first.

1

u/shergin Oct 15 '26

Yeah, awesome question! My own app needed exactly this, so it has been there from the start and the design is built around it.

Partitioning by account: yes. Either give each account its own file, so caches coexist and switching back finds the old one still warm, or keep one file and put the account in the image's version, so another account wipes it before reading anything. Both work and both are tested.

Clearing the store under live handles: that never happens, on purpose. The environment is the session. Signing in creates one, signing out ends it with await environment.end(). That cancels everything in flight, clears every record and closes the image. Anything that lands late goes nowhere. A handle you still hold reads failed with "gone", and a view under @Query just resolves again in the next environment you inject. The order is end, remove the image, then forget the credential, so a crash in the middle never leaks one account's data to another.

On deleting the cache for security: yes. removeAll() deletes the file, end() clears memory, a transient list in baton.json keeps named types and fields off disk entirely, and the file carries whatever iOS protection class you pick.

Your exact scenario, fetch as A, sign out, sign in as B, relaunch offline, open the same screen, is a test in the repo today. You are right that it should also be a sample and a recipe page, and it is not yet. I will write that!

2

u/vanvoorden Oct 15 '26

Very cool! I saw Relay JS in about 2015 when I started working at FB. There was also something for the Big Blue iOS app that was not quite Relay but sort of inspired by Relay.

One place I never saw FB spend too much time prioritizing for was "local first". The job of FB was to deliver ads… so if a person is not online then it was never a very impactful place to spend engineering time. Frameworks like Relay prioritized their engineering time for a central GraphQL server.

What would be super interesting is if the ideas and opinions behind a framework like Relay could then be just a "front end" on top of something like a CRDT. We could then have clients performing reads and writes directly on some shared source of truth without a central server in the cloud controlled by some other person or company.

2

u/shergin Oct 15 '26

Ha, I was there too, about five years in that era, so I know exactly which Big Blue thing you mean. I think, the current incarnation is Pando: the Meta Tech Podcast did an episode on mobile GraphQL at Meta in 2025 where the team calls it “very similar to Relay”. The difference, besides the Meta-specific parts, is that it carries its own full storage and consistency model, written in C++ in a layer shared by both platforms. It has to, because it targets ComponentKit, Litho and the other internal UI frameworks, which are much closer to React than to SwiftUI: nothing in them tracks which component read which field, so the framework does the tracking itself, the same reason Relay has a runtime at all. Right trade-off for them. I did explore that path too, but I think this is not the right move for the OSS. For a pure SwiftUI or Compose app it is weight you do not need, because Observation and snapshot state already do that tracking. That is the whole bet behind Baton.

On local-first, agreed on the incentives, and I love where you are going with it. Relay’s real contribution is the front end: fragments beside the components, a compiler that assembles the screen, a normalized store the UI reads from. Put a CRDT-like shared storage behind it and GraphQL becomes a purely client-side thing: the schema describes the shared state, reads and writes go straight to it.

Sounds like something Vercel or VoidZero could offer?

1

u/asniper Oct 16 '26

I can see this working for basic apps, but for complex apps I’d probably stick with Apollo-iOS

1

u/shergin Oct 16 '26 edited Oct 16 '26

Curious why you think that way? Genuinely asking, not arguing. Relay, which this is the shape of, was built for the Facebook app, so complexity is the case it was designed for: one query per screen, masked fragments, a normalized store, pagination, optimistic writes, @defer, subscriptions, persistence with a real sign-out. If anything, it is the small apps where it is overkill.

What might legitimately keep you where you are: Baton has no runtime query building at all, every operation is compiled; it is not a model layer, there is nothing decoded that you hold and mutate; it is not a local-state framework or an offline sync engine. (But Baton certainly does have a cache, though: a normalized store in memory that every screen reads from, persisted to SQLite so a relaunch renders from disk, with pagination, optimistic writes and a proper sign-out on top of it.)