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
5 changes: 5 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,5 +59,10 @@ export type UseUndoable<T> = [
behavior?: MutationBehavior,
ignoreAction?: boolean
) => void
setStateStable: (
payload: T | ((oldValue: T) => T),
behavior?: MutationBehavior,
ignoreAction?: boolean
) => void
}
]
16 changes: 15 additions & 1 deletion src/useUndoable.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useReducer, useCallback, Reducer } from "react"
import { useReducer, useCallback, Reducer, useRef } from "react"

import { reducer } from "./reducer"

Expand Down Expand Up @@ -95,6 +95,19 @@ const useUndoable = <T = any>(
[state]
)

const setStateRef = useRef(setState)
setStateRef.current = setState;

const setStateStable = useCallback((
payload: any,

// @ts-ignore
mutationBehavior: MutationBehavior = options.behavior,
ignoreAction: boolean = false
) => {
return setStateRef.current(payload, mutationBehavior, ignoreAction)
}, [setStateRef])

// In some rare cases, the fact that the above setState
// function changes on every render can be problematic.
// Since we can't really avoid this (setState uses
Expand Down Expand Up @@ -126,6 +139,7 @@ const useUndoable = <T = any>(
reset,
resetInitialState,
static_setState,
setStateStable
},
]
}
Expand Down