MCPcopy Create free account
hub / github.com/streamich/react-use / useGetSetState

Function useGetSetState

src/useGetSetState.ts:4–30  ·  view source on GitHub ↗
(
  initialState: T = {} as T
)

Source from the content-addressed store, hash-verified

2import useUpdate from './useUpdate';
3
4const useGetSetState = <T extends object>(
5 initialState: T = {} as T
6): [() => T, (patch: Partial<T>) => void] => {
7 if (process.env.NODE_ENV !== 'production') {
8 if (typeof initialState !== 'object') {
9 console.error('useGetSetState initial state must be an object.');
10 }
11 }
12
13 const update = useUpdate();
14 const state = useRef<T>({ ...(initialState as object) } as T);
15 const get = useCallback(() => state.current, []);
16 const set = useCallback((patch: Partial<T>) => {
17 if (!patch) {
18 return;
19 }
20 if (process.env.NODE_ENV !== 'production') {
21 if (typeof patch !== 'object') {
22 console.error('useGetSetState setter patch must be an object.');
23 }
24 }
25 Object.assign(state.current, patch);
26 update();
27 }, []);
28
29 return [get, set];
30};
31
32export default useGetSetState;

Callers 2

DemoFunction · 0.90
setUpFunction · 0.85

Calls 1

useUpdateFunction · 0.85

Tested by 1

setUpFunction · 0.68

Used in the wild real call sites across dependent graphs

searching dependent graphs…