Skip to content

Commit

Permalink
feat(useGetSet): reworked with use of new resolveHookState function p…
Browse files Browse the repository at this point in the history
…lus improved memory usage;
  • Loading branch information
xobotyi committed Oct 30, 2019
1 parent 9fd02eb commit 9b5d0f2
Showing 1 changed file with 17 additions and 12 deletions.
29 changes: 17 additions & 12 deletions src/useGetSet.ts
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();
},
],
[]
);
}

0 comments on commit 9b5d0f2

Please sign in to comment.