| 11 | // We need this in order to setState and reference the updated state multiple |
| 12 | // times in the same function. |
| 13 | export const useStateAndRef = < |
| 14 | // Everything but function. |
| 15 | T extends object | null | undefined | number | string, |
| 16 | >( |
| 17 | initialValue: T, |
| 18 | ) => { |
| 19 | const [_, setState] = React.useState<T>(initialValue); |
| 20 | const ref = React.useRef<T>(initialValue); |
| 21 | |
| 22 | const setStateInternal = React.useCallback<typeof setState>( |
| 23 | (newStateOrCallback) => { |
| 24 | let newValue: T; |
| 25 | if (typeof newStateOrCallback === 'function') { |
| 26 | newValue = newStateOrCallback(ref.current); |
| 27 | } else { |
| 28 | newValue = newStateOrCallback; |
| 29 | } |
| 30 | setState(newValue); |
| 31 | ref.current = newValue; |
| 32 | }, |
| 33 | [], |
| 34 | ); |
| 35 | |
| 36 | return [ref, setStateInternal] as const; |
| 37 | }; |