Something went wrong. Try again.
Starship Simulator Controls thoriumsim.com
Something went wrong. Try again.
1.0 kB · 33 lines
TSX
at develop
12345678910111213141516171819202122232425262728293031323334import { useReducer, useEffect, useCallback, type Reducer } from "react";
export function useLocalStorageReducer<R extends Reducer<I, A>, I, A>( reducer: R, defaultState: I, storageKey: string,) { const init = useCallback(() => { let preloadedState: any; try { preloadedState = JSON.parse(window.localStorage.getItem(storageKey) || ""); // validate preloadedState if necessary } catch { // ignore } if (typeof preloadedState === "string") return preloadedState; if (typeof defaultState === "string") return defaultState; return { ...defaultState, ...preloadedState }; }, [storageKey, defaultState]);
const hookVars = useReducer(reducer, null, init);
const hookyHook = hookVars[0]; useEffect(() => { localStorage.setItem(storageKey, JSON.stringify(hookyHook)); }, [storageKey, hookyHook]);
return hookVars;}
export function useLocalStorage<T>(storageKey: string, defaultValue: T) { return useLocalStorageReducer((state: T, action: any) => action, defaultValue, storageKey);}