Basic Usage
Creating Global Signals
Basic Global Signal
- Must be
staticandconstinitialization - Constructor is a function pointer (not a closure)
- Initialized lazily on first access
Global Memos
Accessing Global State
Direct Access
Getting the Underlying Signal
Some operations require a mutableSignal:
signal() method:
Type Aliases
Complete Example
Common Patterns
Application Settings
User Authentication
Feature Flags
Derived Global State
Initialization from External Sources
Since global signals require function pointers, you can’t capture environment variables directly:Global State vs Context
Use Global State When:
- State is truly application-wide (settings, auth, theme)
- Every component might need access
- State lifetime matches app lifetime
- Single instance is needed
Use Context When:
- State is scoped to a subtree
- Multiple instances might exist (different contexts in different subtrees)
- State might change based on routing
- Library components that need configuration
Performance
- Global state is as fast as regular signals
- Lazy initialization - only created on first access
- Components only rerender when they read values that change
- Zero overhead if never accessed
Limitations
- Constructor must be a function pointer (no closures)
- Can’t capture environment at initialization
- Lives for entire application lifetime (can’t be dropped)
- Not recommended for libraries (makes testing harder)
Library Considerations
Global state makes it difficult to have multiple instances:Testing
Global state persists across tests, which can cause issues:- Reset state in each test
- Use context instead for testable code
- Run tests with
--test-threads=1
Related
- use_signal - Component-scoped signals
- context - Tree-scoped state sharing
- stores - Fine-grained nested state
- use_memo - Computed values