Gpui Global

Manage app-wide state and shared resources in GPUI applications

✨ The solution you've been looking for

Verified
Tested and verified by our team
9771 Stars

Global state management in GPUI. Use when implementing global state, app-wide configuration, or shared resources.

gpui rust state-management global-state configuration frontend ui-framework shared-resources
Repository

See It In Action

Interactive preview & real-world examples

Live Demo
Skill Demo Animation

AI Conversation Simulator

See how users interact with this skill

User Prompt

Help me create a global configuration system for my GPUI app that stores API settings, user preferences, and feature flags

Skill Processing

Analyzing request...

Agent Response

Implementation of a Global trait for app configuration with examples of setting and accessing config values from any component

Quick Start (3 Steps)

Get up and running in minutes

1

Install

claude-code skill install gpui-global

claude-code skill install gpui-global
2

Config

3

First Trigger

@gpui-global help

Commands

CommandDescriptionRequired Args
@gpui-global app-configuration-managementSet up global application settings like API endpoints, themes, and feature flags that need to be accessible throughout your GPUI appNone
@gpui-global shared-service-registryCreate a centralized registry for shared services like HTTP clients, loggers, and database connectionsNone
@gpui-global feature-flag-systemImplement a feature flag system to conditionally render UI elements based on global feature togglesNone

Typical Use Cases

App Configuration Management

Set up global application settings like API endpoints, themes, and feature flags that need to be accessible throughout your GPUI app

Shared Service Registry

Create a centralized registry for shared services like HTTP clients, loggers, and database connections

Feature Flag System

Implement a feature flag system to conditionally render UI elements based on global feature toggles

Overview

Overview

Global state in GPUI provides app-wide shared data accessible from any context.

Key Trait: Global - Implement on types to make them globally accessible

Quick Start

Define Global State

1use gpui::Global;
2
3#[derive(Clone)]
4struct AppSettings {
5    theme: Theme,
6    language: String,
7}
8
9impl Global for AppSettings {}

Set and Access Globals

 1fn main() {
 2    let app = Application::new();
 3    app.run(|cx: &mut App| {
 4        // Set global
 5        cx.set_global(AppSettings {
 6            theme: Theme::Dark,
 7            language: "en".to_string(),
 8        });
 9
10        // Access global (read-only)
11        let settings = cx.global::<AppSettings>();
12        println!("Theme: {:?}", settings.theme);
13    });
14}

Update Globals

 1impl MyComponent {
 2    fn change_theme(&mut self, new_theme: Theme, cx: &mut Context<Self>) {
 3        cx.update_global::<AppSettings, _>(|settings, cx| {
 4            settings.theme = new_theme;
 5            // Global updates don't trigger automatic notifications
 6            // Manually notify components that care
 7        });
 8
 9        cx.notify(); // Re-render this component
10    }
11}

Common Use Cases

1. App Configuration

 1#[derive(Clone)]
 2struct AppConfig {
 3    api_endpoint: String,
 4    max_retries: u32,
 5    timeout: Duration,
 6}
 7
 8impl Global for AppConfig {}
 9
10// Set once at startup
11cx.set_global(AppConfig {
12    api_endpoint: "https://api.example.com".to_string(),
13    max_retries: 3,
14    timeout: Duration::from_secs(30),
15});
16
17// Access anywhere
18let config = cx.global::<AppConfig>();

2. Feature Flags

 1#[derive(Clone)]
 2struct FeatureFlags {
 3    enable_beta_features: bool,
 4    enable_analytics: bool,
 5}
 6
 7impl Global for FeatureFlags {}
 8
 9impl MyComponent {
10    fn render_beta_feature(&self, cx: &App) -> Option<impl IntoElement> {
11        let flags = cx.global::<FeatureFlags>();
12
13        if flags.enable_beta_features {
14            Some(div().child("Beta feature"))
15        } else {
16            None
17        }
18    }
19}

3. Shared Services

 1#[derive(Clone)]
 2struct ServiceRegistry {
 3    http_client: Arc<HttpClient>,
 4    logger: Arc<Logger>,
 5}
 6
 7impl Global for ServiceRegistry {}
 8
 9impl MyComponent {
10    fn fetch_data(&mut self, cx: &mut Context<Self>) {
11        let registry = cx.global::<ServiceRegistry>();
12        let client = registry.http_client.clone();
13
14        cx.spawn(async move |cx| {
15            let data = client.get("api/data").await?;
16            // Process data...
17            Ok::<_, anyhow::Error>(())
18        }).detach();
19    }
20}

Best Practices

✅ Use Arc for Shared Resources

1#[derive(Clone)]
2struct GlobalState {
3    database: Arc<Database>,  // Cheap to clone
4    cache: Arc<RwLock<Cache>>,
5}
6
7impl Global for GlobalState {}

✅ Immutable by Default

Globals are read-only by default. Use interior mutability when needed:

 1#[derive(Clone)]
 2struct Counter {
 3    count: Arc<AtomicUsize>,
 4}
 5
 6impl Global for Counter {}
 7
 8impl Counter {
 9    fn increment(&self) {
10        self.count.fetch_add(1, Ordering::SeqCst);
11    }
12
13    fn get(&self) -> usize {
14        self.count.load(Ordering::SeqCst)
15    }
16}

❌ Don’t: Overuse Globals

1// ❌ Bad: Too many globals
2cx.set_global(UserState { ... });
3cx.set_global(CartState { ... });
4cx.set_global(CheckoutState { ... });
5
6// ✅ Good: Use entities for component state
7let user_entity = cx.new(|_| UserState { ... });

When to Use

Use Globals for:

  • App-wide configuration
  • Feature flags
  • Shared services (HTTP client, logger)
  • Read-only reference data

Use Entities for:

  • Component-specific state
  • State that changes frequently
  • State that needs notifications

Reference Documentation

  • API Reference: See api-reference.md
    • Global trait, set_global, update_global
    • Interior mutability patterns
    • Best practices and anti-patterns

What Users Are Saying

Real feedback from the community

Environment Matrix

Dependencies

GPUI framework
Rust with std library support

Framework Support

GPUI ✓ (required)

Context Window

Token Usage ~2K-3K tokens for typical global state implementations

Security & Privacy

Information

Author
longbridge
Updated
2026-01-30
Category
frontend