@ehfuse/forma
Version:
Advanced React state management library with individual field subscriptions - supports both forms and general state management with useFormaState
110 lines • 5.87 kB
TypeScript
/**
* useFormaState.ts
*
* Advanced state management hook with individual field subscriptions
* Optimized for arrays, objects, and complex nested data structures
*
* @author KIM YOUNG JIN (ehfuse@gmail.com)
* @license MIT License
*/
import { FieldStore } from "../core/FieldStore";
import { FormChangeEvent, ActionContext, Actions } from "../types/form";
/**
* Options for configuring useFormaState hook
* useFormaState 훅 설정을 위한 옵션
*/
export interface UseFormaStateOptions<T extends Record<string, any>> {
/** Optional callback when state changes | 상태 변경 시 선택적 콜백 */
onChange?: (values: T) => void;
/** Enable deep equality checking for better performance | 성능 향상을 위한 깊은 동등성 검사 활성화 */
deepEquals?: boolean;
/** External FieldStore instance for shared state | 공유 상태를 위한 외부 FieldStore 인스턴스 */
_externalStore?: FieldStore<T>;
/** Error handler for state operations | 상태 작업을 위한 에러 핸들러 */
onError?: (error: Error) => void;
/** Enable validation on every change | 모든 변경에 대한 유효성 검사 활성화 */
validateOnChange?: boolean;
/** Custom actions (computed getters and handlers) - can be object or array | 커스텀 액션 (computed getter 및 handler) - 객체 또는 배열 */
actions?: Actions<T> | Actions<T>[];
/** Watch callbacks - detect specific path changes (wildcard supported) | Watch 콜백 - 특정 경로 변경 감지 (와일드카드 지원) */
watch?: Record<string, (context: ActionContext<T>, value: any, prevValue: any) => void | Promise<void>>;
}
/**
* Return type for useFormaState hook
* useFormaState 훅의 반환 타입
*/
export interface UseFormaStateReturn<T extends Record<string, any>> {
/** Subscribe to a specific field with dot notation | dot notation으로 특정 필드 구독 */
useValue: <K extends string>(path: K) => any;
/** Set a specific field value with dot notation | dot notation으로 특정 필드 값 설정 */
setValue: <K extends string>(path: K, value: any) => void;
/** Get all current values (non-reactive) | 모든 현재 값 가져오기 (반응형 아님) */
getValues: () => T;
/** Set all values at once | 모든 값을 한 번에 설정 */
setValues: (values: Partial<T>) => void;
/** Batch update multiple fields efficiently | 여러 필드를 효율적으로 일괄 업데이트 */
setBatch: (updates: Record<string, any>) => void;
/** Reset to initial values | 초기값으로 재설정 */
reset: () => void;
/** Set new initial values (for dynamic initialization) | 새 초기값 설정 (동적 초기화용) */
setInitialValues: (newInitialValues: T) => void;
/** Handle standard input change events | 표준 입력 변경 이벤트 처리 */
handleChange: (event: FormChangeEvent) => void;
/** Check if a field exists | 필드 존재 여부 확인 */
hasField: (path: string) => boolean;
/** Remove a field from state | 상태에서 필드 제거 */
removeField: (path: string) => void;
/** Get a single field value (non-reactive) | 단일 필드 값 가져오기 (반응형 아님) */
getValue: (path: string) => any;
/** Subscribe to all state changes | 모든 상태 변경에 구독 */
subscribe: (callback: (values: T) => void) => () => void;
/** Refresh all field subscribers with specific prefix | 특정 prefix를 가진 모든 필드 구독자들을 새로고침 */
refreshFields: (prefix: string) => void;
/** Custom actions bound to this state | 이 상태에 바인딩된 커스텀 액션 */
actions: any;
/** Direct access to the internal store for advanced usage | 고급 사용을 위한 내부 스토어 직접 접근 */
_store: FieldStore<T>;
}
/**
* Hook for subscribing to a specific field in a FieldStore
* FieldStore의 특정 필드를 구독하기 위한 Hook
*
* @param store FieldStore 인스턴스
* @param path 필드 경로 (dot notation)
* @returns 필드의 현재 값
*/
export declare function useFieldSubscription<T = any>(store: FieldStore<any>, path: string): T;
/**
* Advanced state management hook with individual field subscriptions
* 개별 필드 구독을 통한 고급 상태 관리 훅
*
* Optimized for managing complex arrays, objects, and nested data structures
* where you want to avoid unnecessary re-renders when only specific fields change.
*
* 복잡한 배열, 객체, 중첩된 데이터 구조를 관리하는 데 최적화되어 있으며,
* 특정 필드만 변경될 때 불필요한 재렌더링을 방지하고자 할 때 사용합니다.
*
* @example
* ```typescript
* // Managing an array of users
* const state = useFormaState({
* users: [
* { name: 'John', email: 'john@example.com', age: 30 },
* { name: 'Jane', email: 'jane@example.com', age: 25 }
* ],
* settings: { theme: 'dark', notifications: true }
* });
*
* // Subscribe to individual fields - only these components re-render when changed
* const firstName = state.useValue('users.0.name'); // Only re-renders when John's name changes
* const userAge = state.useValue('users.1.age'); // Only re-renders when Jane's age changes
* const theme = state.useValue('settings.theme'); // Only re-renders when theme changes
*
* // Update specific fields
* state.setValue('users.0.name', 'Johnny');
* state.setValue('settings.theme', 'light');
* ```
*/
export declare function useFormaState<T extends Record<string, any> = Record<string, any>>(initialValues?: T, options?: UseFormaStateOptions<T>): UseFormaStateReturn<T>;
export declare function useFormaState<T extends Record<string, any>>(initialValues: T, options?: UseFormaStateOptions<T>): UseFormaStateReturn<T>;
//# sourceMappingURL=useFormaState.d.ts.map