skip to content

In SwiftUI, when should you use onGeometryChange(for:of:action:) instead of a GeometryReader that writes a size into @State, and why?

level: seniorimportance: should knowfreq 45%

answer

  1. no container, no greedy size
  2. transform, then action
  3. Equatable value gates the action
  4. keep the derived value coarse

basics

~20 s

Use onGeometryChange(for:of:action:) whenever you need a value derived from a view's geometry in state. It adds no container, transforms the proxy into an Equatable value, and runs the action only when that value changes, unlike writing state from a reader's closure.

solid answer

~50 s

`onGeometryChange(for:of:action:)` attaches to the view you measure. Its `of` closure turns the `GeometryProxy` into a value of your own type, which must be `Equatable` and `Sendable`, and its `action` runs when that value changes, so you write `@State` there. Compared with a `GeometryReader`, nothing wraps the view, so the greedy-size problem disappears, and there is no assignment inside a closure SwiftUI calls while building views. Apple's documentation adds the performance angle: geometry can change very often, so transform it into the smallest value you need, such as a `Bool` or a bucket, and the action, plus everything that reads the state, runs rarely. The single-value action works from iOS 16; the form whose action gets old and new values needs iOS 18. Keep a reader where you lay content out from the size, not just read it.

code

swift · 19 lines
swift
struct ShareOptionsSheet: View {
    @State private var contentHeight: CGFloat = 300

    var body: some View {
        VStack(alignment: .leading, spacing: 16) {
            Label("Copy link", systemImage: "link")
            Label("Message", systemImage: "message")
            Label("Mail", systemImage: "envelope")
        }
        .padding(24)
        .frame(maxWidth: .infinity, alignment: .leading)
        .onGeometryChange(for: CGFloat.self) { proxy in
            proxy.size.height
        } action: { newHeight in
            contentHeight = newHeight
        }
        .presentationDetents([.height(contentHeight)])
    }
}

go deeper

for a junior

Recall that onGeometryChange reads a view's geometry without wrapping it, and that its action is where you update state.

for a middle

Explain the two closures: the transform produces an Equatable value from the proxy, and the action runs only when that value changes. Compare it with the background-reader workaround.

for a senior

Show the production judgment: make the transformed value coarse to keep updates rare, avoid loops where the result changes what is measured, know the iOS 16 and iOS 18 forms, and keep GeometryReader for layout from size.

for a principal

Set the team default: onGeometryChange for geometry into state, visualEffect for geometry into rendering, preferences for combining children, and readers only for regions that lay out from their size.

## The pattern it replaces Before `onGeometryChange`, getting a view's size into state took a workaround. A typical version puts a `GeometryReader` in the view's background with a `Color.clear` placeholder, and copies the size from `onAppear` and `onChange`: ```swift .background { GeometryReader { proxy in Color.clear .onAppear { contentHeight = proxy.size.height } .onChange(of: proxy.size.height) { _, newHeight in contentHeight = newHeight } } } ``` It works, but it is three modifiers of ceremony. A shorter, broken version is common in code review: `GeometryReader { proxy in ... }` around the content with `contentHeight = proxy.size.height` written straight into the closure. That closure runs while SwiftUI is building views, so assigning state there is a **side effect during a view update**: it can schedule another update, and Xcode flags it at runtime. And if the reader wraps the content, its flexible size distorts the layout as well. ## What onGeometryChange(for:of:action:) does The modifier takes three parts: - **`for`**: the type of value you want, such as `CGFloat.self` or `Bool.self`. It must be `Equatable` and `Sendable`. - **`of`**: a transform closure, `@Sendable (GeometryProxy) -> T`, that turns the proxy into your value. It has the usual proxy members: `size`, `frame(in:)`, `safeAreaInsets`. - **`action`**: runs **when the transformed value changes**, and is where you write state or call your model. Because the modifier is attached to the view rather than wrapping it, there is **no extra container** and no flexible size to fight. Because the action is gated on an `Equatable` comparison, it runs only when the value you care about changes, not on every geometry change. ## Make the value coarse Apple's documentation is explicit that geometry can change frequently, especially inside a scrolling container, and that you should avoid updating large parts of the app whenever it does. The two closures exist for that reason. Put the reduction in the transform: | Transform returns | Action runs when | Good for | |---|---|---| | `proxy.size` | any size change, to the fraction of a point | rarely the right choice | | `proxy.size.height` | the height changes | sizing a sheet to its content | | `proxy.size.width > 500` | the view crosses the threshold | switching a style flag | | a small enum bucket | the bucket changes | choosing an image or stream size | The coarser the value, the fewer state writes, and the fewer body updates in every view that reads that state. ## A worked case: sizing a sheet to its content A share sheet with three rows should be exactly as tall as its rows. The content measures itself with `onGeometryChange`, the action stores the height, and `presentationDetents([.height(contentHeight)])`, covered with sheets, uses it. The `VStack` hugs its rows, so its height does not depend on the detent, and the value settles after one change. Had the content been a flexible view that fills whatever height it gets, the measured height would follow the detent and the detent the measurement: exactly the loop to avoid. ## Versions and availability 1. The single-value form, whose action receives the new value, is declared from **iOS 16** in the iOS 27 SDK, so it covers the usual iOS 17 floor. 2. A second form, whose action receives **old and new values**, `action: (oldValue, newValue)`, requires **iOS 18**. 3. Neither form needs a `GeometryReader`, and both take the same `@Sendable` transform. ## When a GeometryReader is still right - When you **lay content out from the size**, for example a drawing surface or a chart region that places children at fractions of the width, the reader is the tool, ideally at the root of that region. - When the geometry drives **rendering only**, such as a parallax offset, `visualEffect(_:)` reads it without writing any state. - When several children's measurements must be **combined** for a parent, a `PreferenceKey` does the merging for you. ## Things to watch - **Feedback loops still exist.** If the state you write changes the measured view's size, the action fires again; measure something the result doesn't affect, or make the value coarse enough to settle. - **The transform is `@Sendable`.** Compute from the proxy and constants; read main-actor state in the action instead. - **Scroll metrics have their own callbacks**, covered with scroll views; `onGeometryChange` is for the view's own geometry.

  • What does the iOS 18 form of the action add?
    Its action receives both the old and the new value, so you can react to the direction of a change, for example animate only when a view grows, without storing the previous value yourself. The single-value form, declared from iOS 16, passes only the new value. On an iOS 17 deployment target the old-and-new form needs an availability check.
  • Why must the transform's result be Equatable and Sendable?
    Equatable is how SwiftUI decides whether the value changed and the action should run; that comparison is the whole point of the modifier. Sendable is required because the transform is a `@Sendable` closure and its result crosses from it to the action, so main-actor state belongs in the action, not in the transform.

It is a thermostat rather than a thermometer you keep reading: you set the threshold you care about once, and it only calls you when the room crosses it.

  • Assigning @State inside a GeometryReader's closure is the normal way to store a size
  • onGeometryChange runs its action on every layout pass
  • onGeometryChange wraps the view in a GeometryReader, with the same greedy size
  • Returning the full size is always best because it carries the most information
  • The old-and-new value action works on iOS 16

Assumes the iOS 27 SDK; the single-value onGeometryChange action is available from iOS 16 and the old-and-new-value action form from iOS 18.