Skip to main content
useEnvironment(): EnvironmentValues;

Returns

An EnvironmentValues object with the following fields:
colorScheme
"light" | "dark"
The current appearance mode.
displayScale
number
The display pixel density (e.g. 2.0 for Retina displays).
dynamicTypeSize
DynamicTypeSize
The user’s preferred text size setting. See DynamicTypeSize.
locale
string
The current locale identifier (e.g. "en_US").
layoutDirection
"leftToRight" | "rightToLeft"
Text layout direction.
screen
{ width: number; height: number }
Screen dimensions in points.
platform
string
The current platform (e.g. "iOS", "web", "android").
openURL
(url: string, resultCallback?: (success: boolean) => void) => void
Opens a URL using the platform’s default handler.
Custom environment values set via the .environment() modifier are also available as additional properties on the returned object.

Usage

Adapt to color scheme

const body = () => {
    const env = useEnvironment()
    const isDark = env.colorScheme === "dark"

    return Text("Current theme: " + (isDark ? "Dark" : "Light"))
        .foregroundStyle(Color(isDark ? "white" : "black"))
}

Responsive layout

const body = () => {
    const env = useEnvironment()
    const isCompact = env.screen.width < 400

    return isCompact
        ? VStack({ spacing: 8 }, [
            Text("Title").font("headline"),
            Text("Subtitle").font("subheadline")
        ])
        : HStack({ spacing: 16 }, [
            Text("Title").font("headline"),
            Text("Subtitle").font("subheadline")
        ])
}

Read custom environment values

const body = () => {
    const env = useEnvironment()
    const accentColor = env.accentColor || "blue"

    return Text("Styled text")
        .foregroundStyle(Color(accentColor))
}

Open a URL

const body = () => {
    const env = useEnvironment()

    return Button("Visit Website", () => {
        env.openURL("https://example.com")
    })
}

Notes

  • useEnvironment must be called inside a component body function, not at the top level.
  • Custom values are set via the .environment() modifier on a parent component, e.g. .environment("accentColor", "purple").
  • The screen dimensions are in logical points, not physical pixels.

See Also