| 2 | import useUpdate from './useUpdate'; |
| 3 | |
| 4 | const 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 | |
| 32 | export default useGetSetState; |