Download hooks/useLocalStorage.ts from Severian/Yuki: direct link, hf CLI and curl.
- Browser
- Download file 1.45 kB
-
https://huggingface.co/spaces/Severian/Yuki/resolve/main/hooks/useLocalStorage.ts
- Command line
-
hf download hf://spaces/Severian/Yuki/hooks/useLocalStorage.ts
-
curl -L -o useLocalStorage.ts https://huggingface.co/spaces/Severian/Yuki/resolve/main/hooks/useLocalStorage.ts
1.45 kB
| import { useState, useEffect } from 'react'; | |
| // A hook for persisting state to localStorage, now user-agnostic. | |
| export function useLocalStorage<T>(key: string, initialValue: T): [T, React.Dispatch<React.SetStateAction<T>>] { | |
| // Create a static key. | |
| const storageKey = `yuki-app-${key}`; | |
| const [storedValue, setStoredValue] = useState<T>(() => { | |
| try { | |
| if (typeof window === 'undefined') return initialValue; | |
| const item = window.localStorage.getItem(storageKey); | |
| return item ? JSON.parse(item) : initialValue; | |
| } catch (error) { | |
| console.error(error); | |
| return initialValue; | |
| } | |
| }); | |
| useEffect(() => { | |
| try { | |
| const item = window.localStorage.getItem(storageKey); | |
| if (item) { | |
| setStoredValue(JSON.parse(item)); | |
| } | |
| } catch (error) { | |
| console.error(error); | |
| } | |
| }, [storageKey]); | |
| const setValue: React.Dispatch<React.SetStateAction<T>> = (value) => { | |
| try { | |
| const valueToStore = value instanceof Function ? value(storedValue) : value; | |
| setStoredValue(valueToStore); | |
| if (typeof window !== 'undefined') { | |
| window.localStorage.setItem(storageKey, JSON.stringify(valueToStore)); | |
| } | |
| } catch (error) { | |
| console.error(error); | |
| } | |
| }; | |
| return [storedValue, setValue]; | |
| } |