-
-
Notifications
You must be signed in to change notification settings - Fork 3.2k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(useGetSet): reworked with use of new resolveHookState function p…
…lus improved memory usage;
- Loading branch information
Showing
1 changed file
with
17 additions
and
12 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,16 +1,21 @@ | ||
import { useCallback, useRef } from 'react'; | ||
import { Dispatch, useMemo, useRef } from 'react'; | ||
import useUpdate from './useUpdate'; | ||
import { HookState, InitialHookState, resolveHookState } from './util/resolveHookState'; | ||
|
||
const useGetSet = <T>(initialValue: T): [() => T, (value: T) => void] => { | ||
const state = useRef(initialValue); | ||
export default function useGetSet<S>(initialState: InitialHookState<S>): [() => S, Dispatch<HookState<S>>] { | ||
const state = useRef(resolveHookState(initialState)); | ||
const update = useUpdate(); | ||
const get = useCallback(() => state.current, []); | ||
const set = useCallback((value: T) => { | ||
state.current = value; | ||
update(); | ||
}, []); | ||
|
||
return [get, set]; | ||
}; | ||
|
||
export default useGetSet; | ||
return useMemo( | ||
() => [ | ||
// get | ||
() => state.current as S, | ||
// set | ||
(newState: HookState<S>) => { | ||
state.current = resolveHookState(newState, state.current); | ||
update(); | ||
}, | ||
], | ||
[] | ||
); | ||
} |