-
Notifications
You must be signed in to change notification settings - Fork 188
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
54 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
import * as React from 'react'; | ||
import useEvent from './useEvent'; | ||
|
||
type Updater<T> = T | ((prevValue: T) => T); | ||
|
||
export type SetState<T> = (nextValue: Updater<T>) => void; | ||
|
||
/** | ||
* Same as React.useState but will always get latest state. | ||
* This is useful when React merge multiple state updates into one. | ||
* e.g. onTransitionEnd trigger multiple event at once will be merged state update in React. | ||
*/ | ||
export default function useSyncState<T>( | ||
defaultValue?: T, | ||
): [get: () => T, set: SetState<T>] { | ||
const [, forceUpdate] = React.useReducer(x => x + 1, 0); | ||
|
||
const currentValueRef = React.useRef(defaultValue); | ||
|
||
const getValue = useEvent(() => { | ||
return currentValueRef.current; | ||
}); | ||
|
||
const setValue = useEvent((updater: Updater<T>) => { | ||
currentValueRef.current = | ||
typeof updater === 'function' | ||
? (updater as (prevValue: T) => T)(currentValueRef.current) | ||
: updater; | ||
|
||
forceUpdate(); | ||
}); | ||
|
||
return [getValue, setValue]; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters