react-vite-themes
Version:
A test/experimental React theme system created for learning purposes. Features atomic design components, SCSS variables, and dark/light theme support. Not intended for production use.
44 lines (43 loc) • 1.78 kB
JavaScript
import { useState } from 'react';
export function useLocalStorage(key, initialValue) {
// Get from local storage then parse stored json or return initialValue
const [storedValue, setStoredValue] = useState(() => {
try {
const item = window.localStorage.getItem(key);
if (item === null) {
return initialValue;
}
// Try to parse as JSON first, fallback to string for simple values
try {
return JSON.parse(item);
}
catch {
// If JSON parsing fails, return the raw string (for simple string values)
return item;
}
}
catch (error) {
console.log(`Error reading localStorage key "${key}":`, error);
return initialValue;
}
});
// Return a wrapped version of useState's setter function that persists the new value to localStorage
const setValue = (value) => {
try {
// Allow value to be a function so we have the same API as useState
const valueToStore = value instanceof Function ? value(storedValue) : value;
setStoredValue(valueToStore);
// Store as JSON for complex objects, as string for simple values
if (typeof valueToStore === 'string' || typeof valueToStore === 'number' || typeof valueToStore === 'boolean') {
window.localStorage.setItem(key, String(valueToStore));
}
else {
window.localStorage.setItem(key, JSON.stringify(valueToStore));
}
}
catch (error) {
console.log(`Error setting localStorage key "${key}":`, error);
}
};
return [storedValue, setValue];
}