diff --git a/src/adapters/react.ts b/src/adapters/react.ts index e61dd30..3cd97b2 100644 --- a/src/adapters/react.ts +++ b/src/adapters/react.ts @@ -2,6 +2,33 @@ import { useSyncExternalStore } from 'react' import { Selector } from '../store' // Store 클래스를 가져올 경로 지정 import { StoreApi } from '../createStore' +/** + * A custom hook that subscribes to a store and triggers a rerendering when the state changes. + * You can also provide a selector to subscribe to a partial change of the state. + * + * @param store - The state store implementing the `StoreApi` interface. + * @param selector - Optional function to select a part of the store's state. Defaults to returning the entire state. + * + * @returns The selected state or the entire state if no selector is provided. + * + * @example + * ```ts + * const store = createStore(0); + * + * function Component() { + * const count = useReactive(store); + * + * return
{count}
; + * } + * + * // With a selector + * function SelectedComponent() { + * const evenCount = useReactive(store, (state) => state % 2 === 0); + * + * return
{evenCount ? "Even" : "Odd"}
; + * } + * ``` + */ export function useReactive( store: StoreApi, selector: Selector = (state) => state as unknown as O diff --git a/src/createStore.ts b/src/createStore.ts index 498a702..9ac7d65 100644 --- a/src/createStore.ts +++ b/src/createStore.ts @@ -11,6 +11,25 @@ export interface StoreApi { type Action = (set: SetState) => Record void> type InferActions = A extends (set: SetState) => infer U ? U : never +/** + * Creates a new store with the given initial state and optional actions. + * + * @param initialValue - The initial state value. + * @param actions - Optional actions to update the state. + * + * @returns The store API and any actions if provided. + * + * @example + * ```ts + * const store = createStore(0, (set) => ({ + * inc: (prev) => set(prev + 1), + * dec: (prev) => set(prev - 1), + * })); + * + * store.inc(); // Increments the state + * store.dec(); // Decrements the state + * ``` + */ export const createStore = | undefined>( initialValue: T, actions?: A @@ -33,4 +52,4 @@ export const createStore = | undefined>( return baseStore as A extends Action ? StoreApi & InferActions : StoreApi -} +} \ No newline at end of file