useStateWithHistory
상태와 상태 변경 이력을 관리하는 훅입니다.
상태 변경 시마다 이력이 저장되며, 상태 히스토리를 이전(back
)과 다음(forward
)으로 이동할 수 있습니다. 또한 특정 시점의 상태로 이동(goToIndex
)할 수 있으며, 저장되는 이력의 최대 개수(capacity
)를 제한할 수 있습니다.
Code
Interface
typescript
interface UseStateWithHistoryReturn<T> {
state: T;
setState: (newState: T | ((prevState: T) => T)) => void;
back: () => void;
forward: () => void;
goToIndex: (index: number) => void;
}
typescript
function useStateWithHistory<T>(
initialValue: T | (() => T),
capacity?: number): UseStateWithHistoryReturn<T>;
Usage
typescript
import { useStateWithHistory } from '@modern-kit/react'
const Example = () => {
const { state, setState, back, forward, goToIndex } = useStateWithHistory(0, 5);
return (
<div>
<p>{state}</p>
<button onClick={() => setState(state + 1)}>증가</button>
<button onClick={back}>이전 상태로 이동</button>
<button onClick={forward}>다음 상태로 이동</button>
<button onClick={() => goToIndex(0)}>첫 번째 상태로 이동</button>
</div>
)
}
Example
0