diff --git a/src/useStateWithHistory.ts b/src/useStateWithHistory.ts index 7e2b442cbf..8d17299a61 100644 --- a/src/useStateWithHistory.ts +++ b/src/useStateWithHistory.ts @@ -30,7 +30,8 @@ export function useStateWithHistory( } const isFirstMount = useFirstMountState(); - const [state, innerSetState] = useState(initialState as S); + const [state, innerSetState] = useState(resolveHookState(initialState) as S); + const history = useRef((initialHistory ?? []) as S[]); const historyPosition = useRef(0); @@ -38,8 +39,8 @@ export function useStateWithHistory( if (isFirstMount) { if (history.current.length) { // if last element of history !== initial - push initial to history - if (history.current[history.current.length - 1] !== initialState) { - history.current.push(initialState as I); + if (history.current[history.current.length - 1] !== state) { + history.current.push(state as I); } // if initial history bigger that capacity - crop the first elements out @@ -48,7 +49,7 @@ export function useStateWithHistory( } } else { // initiate the history with initial state - history.current.push(initialState as I); + history.current.push(state); } historyPosition.current = history.current.length && history.current.length - 1; diff --git a/tests/useStateWithHistory.test.ts b/tests/useStateWithHistory.test.ts index 5261daa8dc..a2f4ae8d65 100644 --- a/tests/useStateWithHistory.test.ts +++ b/tests/useStateWithHistory.test.ts @@ -172,6 +172,12 @@ describe('useStateWithHistory', () => { }); expect(hook.result.current[0][0]).toBe(1); }); + + it('should not contain function as initial state', () => { + let hook = getHook(() => 1, 3); + + expect(hook.result.current[0][2].history[0]).toEqual(1); + }); }); describe('history.forward()', () => {