Context Hooks
Context hooks let you observe and modify context tree operations - every insert, update, and delete that happens to the PACT structure.Overview
Context hooks provide 5 execution points:| Hook | Fires | Use Case |
|---|---|---|
before_change | Before any operation | Validation, authorization, logging |
after_change | After any operation | Auditing, reactive updates, cleanup |
on_add | Component added | Tracking additions, indexing |
on_dispatch | Component dispatched | Event handling, notifications |
on_update | Component updated | Change tracking, versioning |
Hook Registration
Decorator Syntax
Subscribe API
Context Hook Context
Every context hook receives aContextExecContext with:
Execution Flow
Before Change Hook
Fires before any context operation - can cancel by raising exception:After Change Hook
Fires after any context operation - for auditing and reactive updates:On Add Hook
Fires when a component is added to context:On Dispatch Hook
Fires when a component is dispatched/published:On Update Hook
Fires when a component is updated:Usage Patterns
Pattern 1: Context Size Monitoring
Track context tree size and warn on growth:Pattern 2: Change History Tracking
Maintain complete history of context modifications:Pattern 3: Reactive Scaffold Updates
Trigger scaffold re-renders on context changes:Pattern 4: Component Validation
Enforce component structure rules:Pattern 5: Depth-Based Policies
Apply different rules based on context depth:Pattern 6: Context Snapshots
Automatically create snapshots on significant changes:Reactive Scaffolds
Context hooks are the foundation of reactive scaffolds - all scaffolds with_reactive = True automatically re-render on context changes:
CONTEXT_AFTER_CHANGEhook fires on every context modification- Reactive scaffolds check
should_rerender(ctx) - If True, scaffold’s
render()is called automatically - New content updates context tree
Operation Types
Context hooks fire for three operation types:Insert Operations
Update Operations
Delete Operations
Best Practices
Use before_change for validation, after_change for reactions
Use before_change for validation, after_change for reactions
Keep before_change hooks fast
Keep before_change hooks fast
Use operation_type to filter events
Use operation_type to filter events
Access full context tree via ctx.context
Access full context tree via ctx.context
Performance Considerations
- Hook overhead: Less than 3ms per hook on average
- before_change blocking: Blocks operation until completed
- after_change async: Runs after operation completes
- Reactive scaffolds: Less than 5% overhead with 5+ scaffolds
Integration with Scaffolds
Context hooks enable reactive scaffolds:Error Handling
Errors inbefore_change cancel the operation:

