Principle:Langgenius Dify ReactPatterns
| Knowledge Sources | Dify |
|---|---|
| Domains | Frontend, React |
| Last Updated | 2026-02-12 07:00 GMT |
Overview
Dify establishes reusable React patterns including typed context factories with automatic error boundaries that eliminate boilerplate and enforce consistent context usage across the application.
Description
The primary React pattern in Dify is the typed context factory implemented in utils/context.ts. The createCtx function generates a tuple of [Provider, useContextValue, Context] from a single generic type parameter and optional configuration. Rather than requiring each feature to manually create a context, define a provider, and write a custom hook with null-check boilerplate, the factory handles all of this automatically. When a component calls useContextValue() outside of the corresponding Provider, the hook throws a descriptive error identifying the missing context by name, functioning as a built-in error boundary for context misuse.
The factory supports two variants: createCtx (standard React useContext) and createSelectorCtx (using use-context-selector for performance-optimized selective re-rendering). Both share the same API surface, allowing developers to upgrade from standard context to selector-based context without changing consumer code. The returned tuple also exposes named properties (.context, .provider, .useContextValue) for destructuring flexibility.
This pattern is used extensively throughout the Dify frontend for feature-specific state management (app context, workspace context, global public context, i18n context, etc.), ensuring that every context follows the same creation pattern, provides the same error messaging, and supports the same consumption API. The consistency reduces cognitive load when navigating between features and makes context-related bugs immediately identifiable through the thrown error messages.
Usage
Use this principle when:
- Creating new feature-level or page-level React contexts that need typed provider/consumer pairs
- Deciding between standard context and selector-based context for performance optimization
- Establishing consistent error handling for missing context providers in component trees
Theoretical Basis
The context factory implements the Factory Method design pattern applied to React's Context API. By encapsulating context creation behind a generic factory function, it achieves the Don't Repeat Yourself (DRY) principle across dozens of context definitions. The automatic error throwing on missing providers implements the Fail Fast principle, ensuring that context misuse is caught during development rather than manifesting as subtle undefined bugs at runtime.