( key: string, initialState: S | ((value?: unknown, rawValue?: unknown) => S) )
| 98 | // and the second argument will be the raw value from localStorage. This is useful for cases where you may |
| 99 | // want to recover the error, apply a transformation or use an alternative parsing function. |
| 100 | export function useLocalStorageState<S>( |
| 101 | key: string, |
| 102 | initialState: S | ((value?: unknown, rawValue?: unknown) => S) |
| 103 | ): [S, (value: S | ((prevState: S) => S)) => void] { |
| 104 | const [value, setValue] = useState(() => { |
| 105 | return initializeStorage<S>(key, initialState); |
| 106 | }); |
| 107 | |
| 108 | // We want to avoid a blinking state with the old value when props change, so we reinitialize the state |
| 109 | // before the screen updates using useLayoutEffect vs useEffect. The ref prevents this from firing on mount |
| 110 | // as the value will already be initialized from the initialState and it would be unnecessary to re-initialize |
| 111 | const renderRef = useRef(false); |
| 112 | useLayoutEffect(() => { |
| 113 | if (!renderRef.current) { |
| 114 | renderRef.current = true; |
| 115 | return; |
| 116 | } |
| 117 | |
| 118 | setValue(initializeStorage(key, initialState)); |
| 119 | // We only want to update the value when the key changes |
| 120 | // eslint-disable-next-line react-hooks/exhaustive-deps |
| 121 | }, [key]); |
| 122 | |
| 123 | const setStoredValue = useCallback( |
| 124 | (newValue: S | ((prevState: S) => S)) => { |
| 125 | if (typeof key !== 'string') { |
| 126 | throw new TypeError('useLocalStorage: key must be a string'); |
| 127 | } |
| 128 | |
| 129 | if (typeof newValue === 'function') { |
| 130 | setValue(p => { |
| 131 | // should be storing functions in state... |
| 132 | // Not critical and we dont want to block anything after this, so fire microtask |
| 133 | // and allow this to eventually be in sync. |
| 134 | // @ts-expect-error TS(2349): This expression is not callable. |
| 135 | const newlyComputedValue = newValue(p); |
| 136 | scheduleMicroTask(() => { |
| 137 | localStorageWrapper.setItem(key, stringifyForStorage(newlyComputedValue)); |
| 138 | }); |
| 139 | return newlyComputedValue; |
| 140 | }); |
| 141 | } else { |
| 142 | setValue(newValue); |
| 143 | // Not critical and we dont want to block anything after this, so fire microtask |
| 144 | // and allow this to eventually be in sync. |
| 145 | scheduleMicroTask(() => { |
| 146 | localStorageWrapper.setItem(key, stringifyForStorage(newValue)); |
| 147 | }); |
| 148 | } |
| 149 | }, |
| 150 | [key] |
| 151 | ); |
| 152 | |
| 153 | return [value, setStoredValue]; |
| 154 | } |
no test coverage detected