Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions src/adapters/react.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 <div>{count}</div>;
* }
*
* // With a selector
* function SelectedComponent() {
* const evenCount = useReactive(store, (state) => state % 2 === 0);
*
* return <div>{evenCount ? "Even" : "Odd"}</div>;
* }
* ```
*/
export function useReactive<T, O = T>(
store: StoreApi<T>,
selector: Selector<T, O> = (state) => state as unknown as O
Expand Down
21 changes: 20 additions & 1 deletion src/createStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,25 @@ export interface StoreApi<T> {
type Action<T> = (set: SetState<T>) => Record<string, (prevState: T) => void>
type InferActions<T, A> = A extends (set: SetState<T>) => 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 = <T, A extends Action<T> | undefined>(
initialValue: T,
actions?: A
Expand All @@ -33,4 +52,4 @@ export const createStore = <T, A extends Action<T> | undefined>(
return baseStore as A extends Action<T>
? StoreApi<T> & InferActions<T, A>
: StoreApi<T>
}
}