MCPcopy Index your code
hub / github.com/react/react / useLocalStorage

Function useLocalStorage

packages/react-devtools-shared/src/devtools/views/hooks.js:145–217  ·  view source on GitHub ↗
(
  key: string,
  initialValue: T | (() => T),
  onValueSet?: (any, string) => void,
)

Source from the content-addressed store, hash-verified

143
144// Forked from https://usehooks.com/useLocalStorage/
145export function useLocalStorage<T>(
146 key: string,
147 initialValue: T | (() => T),
148 onValueSet?: (any, string) => void,
149): [T, (value: T | (() => T)) => void] {
150 const getValueFromLocalStorage = useCallback(() => {
151 try {
152 const item = localStorageGetItem(key);
153 if (item != null) {
154 return JSON.parse(item);
155 }
156 } catch (error) {
157 console.log(error);
158 }
159 if (typeof initialValue === 'function') {
160 return ((initialValue: any): () => T)();
161 } else {
162 return initialValue;
163 }
164 }, [initialValue, key]);
165
166 const storedValue = useSyncExternalStore(
167 useCallback(
168 function subscribe(callback) {
169 window.addEventListener(key, callback);
170 return function unsubscribe() {
171 window.removeEventListener(key, callback);
172 };
173 },
174 [key],
175 ),
176 getValueFromLocalStorage,
177 );
178
179 const setValue = useCallback(
180 (value: $FlowFixMe) => {
181 try {
182 const valueToStore =
183 value instanceof Function ? (value: any)(storedValue) : value;
184 localStorageSetItem(key, JSON.stringify(valueToStore));
185
186 // Notify listeners that this setting has changed.
187 window.dispatchEvent(new Event(key));
188
189 if (onValueSet != null) {
190 onValueSet(valueToStore, key);
191 }
192 } catch (error) {
193 console.log(error);
194 }
195 },
196 [key, storedValue],
197 );
198
199 // Listen for changes to this local storage value made from other windows.
200 // This enables the e.g. "⚛ Elements" tab to update in response to changes from "⚛ Settings".
201 useLayoutEffect(() => {
202 // $FlowFixMe[missing-local-annot]

Callers 7

DevTools.jsFile · 0.90
SettingsModalImplFunction · 0.90
CodeEditorByDefaultFunction · 0.90
GeneralSettings.jsFile · 0.90
useLocalStorageWithLogFunction · 0.90

Calls 5

useCallbackFunction · 0.90
localStorageGetItemFunction · 0.90
useSyncExternalStoreFunction · 0.90
localStorageSetItemFunction · 0.90
useLayoutEffectFunction · 0.90

Tested by

no test coverage detected