Revolutionary TypeScript state management with document-centric context separation and MVVM architecture.
๐ฏ Perfect separation of concerns โข ๐ Full type safety โข โก Zero boilerplate โข ๐๏ธ Scalable architecture
๐ Documentation โข ๐ฐ๐ท ํ๊ตญ์ด ๋ฌธ์ โข ๐ฎ Live Demo โข ๐ Quick Start
npm install @context-action/react
# or
npm install @context-action/core # Pure TypeScriptimport { createStoreContext, useStoreValue } from '@context-action/react';
import { useCallback } from 'react';
// 1. Create context
const { Provider, useStore } = createStoreContext('User', {
profile: { name: 'John', email: 'john@example.com' }
});
// 2. Use in component
function UserProfile() {
const profileStore = useStore('profile');
const profile = useStoreValue(profileStore);
return <h1>Welcome, {profile.name}!</h1>;
}
// 3. Wrap with provider
function App() {
return (
<Provider>
<UserProfile />
</Provider>
);
}That's it! ๐ Full type safety, reactive updates, and clean architecture.
- High React Coupling โ Difficult component modularization
- Binary State Approach โ Poor scope-based separation
- Complex Boilerplate โ Verbose setup and maintenance
- ๐ฏ Document-Centric Design โ Context separation based on domain boundaries
- ๐๏ธ MVVM Architecture โ Perfect separation: Model, ViewModel, View layers
- ๐ Type-First Approach โ Zero runtime errors with full TypeScript support
- โก Zero Boilerplate โ Minimal code, maximum functionality
// Before: Complex setup with multiple libraries
const store = createStore(reducer);
const dispatch = useDispatch();
const selector = useSelector(state => state.user);
const actions = bindActionCreators(userActions, dispatch);
// After: One line with Context-Action
const { profile, updateProfile } = useUserPage(); // All logic in hookPure state management with reactive subscriptions
const { Provider: UserStoreProvider, useStore: useUserStore } = createStoreContext('User', {
profile: { name: '', email: '' },
settings: { theme: 'light' }
});
function UserComponent() {
const profileStore = useUserStore('profile');
const profile = useStoreValue(profileStore);
return <div>{profile.name}</div>;
}Pure action dispatching with business logic separation
interface UserActions extends ActionPayloadMap {
updateProfile: { name: string; email: string };
logout: void;
}
const { Provider, useActionDispatch, useActionHandler } =
createActionContext<UserActions>('UserActions');
function UserLogic() {
const updateProfileHandler = useCallback(async (payload) => {
// Business logic here
await updateUserAPI(payload);
}, []);
useActionHandler('updateProfile', updateProfileHandler);
return null; // Logic component
}Combine patterns for complex applications
// MVVM Architecture
function App() {
return (
<UserActionProvider> {/* ViewModel */}
<UserStoreProvider> {/* Model */}
<UserLogic> {/* Business Logic */}
<UserProfile /> {/* View */}
</UserLogic>
</UserStoreProvider>
</UserActionProvider>
);
}Context-Action implements a sophisticated 5-layer hooks architecture that provides perfect separation of concerns and optimal performance through delayed evaluation.
graph TD
%% Context Share Layer
subgraph ContextShare["Context Share Layer Provider"]
Store[Store]
subgraph ActionsContainer["Actions"]
Actions[Actions]
Pipeline[Pipeline<br/>- Business logic registration<br/>- Execution order management<br/>- Middleware processing]
end
Ref[Ref<br/>- Singleton instance management]
end
%% 6-Layer Hooks Structure
subgraph Hooks["6-Layer Hooks Consumer"]
ContextDef[contexts<br/>Resource type definitions]
Business[business<br/>Pure business logic<br/>functions]
Handlers[handlers<br/>Handler injection pattern<br/>implementation]
Actions[actions<br/>Action dispatch<br/>callback functions]
Subscriptions[hooks<br/>Store subscriptions<br/>computed values]
Views[views<br/>Pure UI components]
end
%% UI Layer
subgraph UI["UI Layer - views"]
Page[Page - route]
Layout[Layout - device Layer]
Widget[Widget - design system]
end
%% Data Flow
Store -->|State management| ContextDef
ContextDef -->|Type definitions| Business
Business -->|Pure functions| Handlers
Handlers -->|Handler injection| Actions
Actions -->|Action execution| Pipeline
Pipeline -->|Pipeline execution| Store
Store -->|Subscription| Subscriptions
Subscriptions -->|Data transfer| Views
Views -->|UI rendering| UI
Actions -->|Action dispatch| Pipeline
%% UI Mount Order
Page -->|Mount| Layout
Layout -->|Mount| Widget
-
Context Share Layer (Provider)
- Store: Centralized state management with reactive subscriptions
- Actions/Pipeline: Business logic registration and execution order management
- Ref: Singleton instance management for performance optimization
-
6-Layer Hooks Structure (Consumer)
- contexts: Resource type definitions and context access
- business: Pure business logic functions separated from side effects
- handlers: Handler injection pattern implementation with latest value access
- actions: Action dispatch functions and callback management
- hooks: Store subscriptions and computed values for reactive data
- views: Pure UI components with minimal coupling
-
UI Layer (Views)
- Page: Route-level components
- Layout: Device-specific layout components
- Widget: Design system components
- Delayed Evaluation: Handlers access latest state via
store.getValue() - Selective Subscriptions: Components subscribe only to needed state slices
- Minimal Re-renders: Optimized dependency tracking prevents unnecessary updates
- Singleton Management: Ref layer ensures efficient resource sharing
// 6-Layer Implementation Example
function UserPage() {
// Layer 1: contexts - Resource type definitions
const userStore = useUserStore('profile');
// Layer 2: handlers - Internal function definitions
const updateUserHandler = useCallback(async (payload) => {
const currentUser = userStore.getValue(); // Delayed evaluation
const updatedUser = { ...currentUser, ...payload };
userStore.setValue(updatedUser);
}, [userStore]);
// Layer 3: subscriptions - Selective state subscriptions
const user = useStoreValue(userStore);
// Layer 4: registries - Handler registration
useActionHandler('updateUser', updateUserHandler);
// Layer 5: dispatchers - View-oriented action dispatchers
const onUpdateUser = useActionDispatch('updateUser');
return (
<div>
<h1>{user.name}</h1>
<button onClick={() => onUpdateUser({ name: 'New Name' })}>
Update User
</button>
</div>
);
}Context-Action implements a sophisticated type system that provides full TypeScript safety across Action, Store, and Ref connections with zero runtime overhead.
graph TB
%% Type Declaration Layer
subgraph TypeDeclarations["๐ค Type Declaration Layer"]
PayloadMap[ActionPayloadMap<br/>Action payload type map]
StoreTypes[StoreDefinitions<br/>Store type definitions]
RefTypes[Ref Types<br/>Singleton reference types]
end
%% Context Creation Layer
subgraph ContextCreation["โ๏ธ Context Creation Layer"]
ActionContext[createActionContext<T><br/>Action context creation]
StoreContext[createStoreContext<T><br/>Store context creation]
RefManager[RefManager<T><br/>Reference manager]
end
%% Hook Layer
subgraph HookLayer["๐ช Hook Layer"]
ActionHooks[useActionDispatch<br/>useActionHandler]
StoreHooks[useStore<br/>useStoreValue]
RefHooks[useRef<br/>useCallback]
end
%% Type Flow Connections
PayloadMap -->|extends| ActionContext
StoreTypes -->|initialStores| StoreContext
RefTypes -->|singleton| RefManager
ActionContext -->|typed hooks| ActionHooks
StoreContext -->|typed hooks| StoreHooks
RefManager -->|stable refs| RefHooks
%% Type Safety Flow
ActionHooks -->|type-safe dispatch| PayloadMap
StoreHooks -->|reactive types| StoreTypes
RefHooks -->|stable references| RefTypes
// 1๏ธโฃ Define Action Payload Types
interface UserActions extends ActionPayloadMap {
updateProfile: { name: string; email: string; avatar?: File };
deleteAccount: { confirmPassword: string };
logout: void; // No payload
}
// 2๏ธโฃ Create Typed Action Context
const {
Provider: UserActionProvider,
useActionDispatch: useUserAction,
useActionHandler: useUserActionHandler
} = createActionContext<UserActions>('UserActions');
// 3๏ธโฃ Type-Safe Handler Registration
function UserLogic() {
// โ
Payload automatically typed as { name: string; email: string; avatar?: File }
useUserActionHandler('updateProfile', useCallback(async (payload) => {
// payload.name โ
string
// payload.email โ
string
// payload.avatar โ
File | undefined
await updateUserAPI(payload);
}, []));
// โ
Payload automatically typed as void
useUserActionHandler('logout', useCallback(async () => {
await clearSession();
}, []));
}
// 4๏ธโฃ Type-Safe Action Dispatching
function UserComponent() {
const dispatch = useUserAction();
return (
<button onClick={() =>
dispatch('updateProfile', {
name: 'John',
email: 'john@example.com'
// โ
TypeScript enforces correct payload shape
})
}>
Update Profile
</button>
);
}// 1๏ธโฃ Define Store Types (Two Approaches)
// Approach A: Simple Object Types
const { Provider, useStore } = createStoreContext('User', {
profile: { name: '', email: '', isOnline: false }, // โ
Type inferred
settings: { theme: 'light' as const, notifications: true }, // โ
const assertions
preferences: { language: 'en', timezone: 'UTC' }
});
// Approach B: Explicit Store Configuration
interface UserStoreConfig {
profile: StoreConfig<UserProfile>;
settings: StoreConfig<UserSettings>;
cache: StoreConfig<CacheData>; // โ
With strategy configuration
}
const { Provider, useStore } = createStoreContext('User', {
profile: { initialValue: { name: '', email: '' } },
settings: { initialValue: { theme: 'light' }, strategy: 'shallow' },
cache: { initialValue: new Map(), strategy: 'reference' }
} satisfies UserStoreConfig);
// 2๏ธโฃ Type-Safe Store Access & Subscription
function UserProfile() {
const profileStore = useStore('profile'); // โ
Store<UserProfile>
const profile = useStoreValue(profileStore); // โ
UserProfile type
// โ
Type-safe store operations
profileStore.setValue({ name: 'John', email: 'john@example.com', isOnline: true });
profileStore.update(prev => ({ ...prev, isOnline: !prev.isOnline }));
return <div>{profile.name}</div>; // โ
profile.name is string
}// 1๏ธโฃ Ref Type Declarations for Singleton Resources
interface AppRefs {
apiClient: ApiClient;
eventBus: EventBus;
cache: LRUCache<string, any>;
}
// 2๏ธโฃ Context with Ref Management
const {
Provider: AppProvider,
useStore,
useRef: useAppRef
} = createStoreContext('App', {
user: { name: '', email: '' },
// โ
Ref types managed alongside stores
}, {
refs: {
apiClient: () => new ApiClient(),
eventBus: () => new EventBus(),
cache: () => new LRUCache(1000)
} as AppRefs
});
// 3๏ธโฃ Type-Safe Ref Access
function ApiComponent() {
const apiClient = useAppRef('apiClient'); // โ
ApiClient type
const userStore = useStore('user');
const fetchUser = useCallback(async (id: string) => {
// โ
apiClient.get is typed method
const userData = await apiClient.get(`/users/${id}`);
userStore.setValue(userData);
}, [apiClient, userStore]);
return <button onClick={() => fetchUser('123')}>Fetch User</button>;
}- โ Action Payload Validation: Incorrect payload shapes caught at compile time
- โ Store Type Consistency: Store value types enforced across components
- โ Ref Type Stability: Singleton reference types maintained across re-renders
- โ Hook Return Types: All hooks return properly typed values and functions
- ๐ Auto-completion: Full IntelliSense for action names, payload properties, store keys
- ๐ท๏ธ Type Hints: Hover information shows exact payload and store types
โ ๏ธ Error Prevention: TypeScript prevents runtime errors before they happen- ๐ Refactoring Safety: Type-safe refactoring across the entire codebase
- โก Compile-Time Only: All type information removed in production builds
- ๐ฆ No Type Libraries: No runtime type checking dependencies
- ๐ฏ Direct Performance: Types guide optimization without runtime cost
For comprehensive type system coverage, see our dedicated guides:
- ๐ TypeScript Type Inference Guide - Complete type inference overview
- ๐ฏ Action Type System - ActionPayloadMap, pipeline controllers, and handler types
- ๐ง Advanced Type Features - Branded types, conditional processing, and utilities
- ๐ก๏ธ Type Safety Best Practices - Essential recommendations and patterns
- ๐ฏ Action Type System - ActionPayloadMap, type safety, TypeScript integration
- Action Type Safety: Complete
ActionPayloadMapinterface with pipeline controller types - Store Type Inference: Automatic type inference from initial values with strategy support
- Handler Configuration: Type-safe handler registration with comprehensive options
- Integration Patterns: Store integration, async handling, and error management
- Advanced Features: Conditional types, branded types, and generic utilities
Create typed store context with reactive subscriptions.
const { Provider, useStore } = createStoreContext('App', {
user: { name: '', email: '' },
settings: { theme: 'light' }
});Create typed action context with pipeline processing.
interface Actions extends ActionPayloadMap {
update: { id: string };
}
const { Provider, useActionDispatch } = createActionContext<Actions>('App');Subscribe to store changes with automatic re-renders.
const userStore = useStore('user');
const user = useStoreValue(userStore); // Reactive subscriptionRegister business logic handlers for actions.
const updateProfileHandler = useCallback(async (payload) => {
// Business logic here
}, []);
useActionHandler('updateProfile', updateProfileHandler);Dispatch actions to the pipeline.
const dispatch = useActionDispatch();
dispatch('updateProfile', { name: 'John', email: 'john@example.com' });Explore 20+ working examples โ
- Store Basics - Fundamental operations
- Store Full Demo - Complex state management
- Declarative Pattern - Type-safe patterns
- Core Features - Pipeline fundamentals
- Action Guards - Advanced filtering
- Priority System - Performance optimization
- Unified Pattern - Complete MVVM demo
- Enhanced Context - Advanced patterns
// E-commerce Cart System
const CartStores = createStoreContext('Cart', {
items: [] as CartItem[],
total: 0,
shipping: { method: 'standard', cost: 0 }
});
// User Management System
interface UserActions extends ActionPayloadMap {
login: { email: string; password: string };
updateProfile: Partial<UserProfile>;
logout: void;
}- ๐ Logger System Demo - Interactive LogMonitor showcase
- Real-time log collection - Live demo with practical examples
- Integration patterns - Parent/Child handler implementations
- Dependency warnings - Avoid infinite loops with best practices
Context-Action Framework implements multiple architectural approaches for different application needs:
Context-Driven Architecture - Core frontend architecture for clear document-based separation
Philosophy: "The document is the architecture" - Each context exists as a unit for managing documents and deliverables of its domain.
Key Features:
- Document-Centric Context Separation: Clear boundaries between domain contexts
- 6-Layer Hooks Architecture: Provider/Consumer pattern with delayed evaluation
- Domain Context Isolation: Business, UI, Validation, Design, Architecture contexts
- Effective Artifact Management: State management supporting document-deliverable relationships
- Context-Layered Architecture - Practical 6-layer implementation guide
- Folder Structure Guide - Organized project structure
- Handler Registry Management - ID and priority management
- ๐ Official Documentation - Complete API reference
- ๐ Getting Started Guide - 5-minute setup
- ๐๏ธ MVVM Core Architecture - Practical MVVM implementation guide
- ๐ Architecture Overview - Framework concepts
- โก Best Practices - Production patterns
- ๐บ๐ธ English Documentation - Complete English guides
- ๐ฐ๐ท Korean Documentation - Complete Korean guide
Pure TypeScript action pipeline - Framework agnostic core
npm install @context-action/core- ๐ Full TypeScript support
- โก Action pipeline system
- ๐ก๏ธ Advanced action guards
- ๐ซ Zero dependencies
React integration - Complete MVVM architecture
npm install @context-action/react- ๐ช Declarative store patterns
- ๐ฏ Action context integration
- ๐ช Advanced React hooks
- ๐๏ธ HOC support
git clone https://github.com/mineclover/context-action.git
cd context-action
pnpm install
pnpm dev # Start example app- ๐ค Contributing Guide - How to contribute
- ๐ Ecosystem - Tools and generators
- ๐ ๏ธ Development Guide - Detailed development setup
Apache-2.0 ยฉ mineclover
Built with โค๏ธ for modern TypeScript applications
โญ Star on GitHub โข ๐ Report Bug โข ๐ก Request Feature