reactuals
Version:
A useful package providing a collection of 50+ React hooks and utilities to simplify React development.
28 lines (27 loc) • 716 B
JavaScript
import { useState } from "react";
/**
* Syncs a value with localStorage.
* @param key - Storage key
* @param initialValue - Default value
*/
export function useLocalStorage(key, initialValue) {
const [storedValue, setStoredValue] = useState(() => {
try {
const item = localStorage.getItem(key);
return item !== null ? JSON.parse(item) : initialValue;
}
catch {
return initialValue;
}
});
const setValue = (value) => {
try {
setStoredValue(value);
localStorage.setItem(key, JSON.stringify(value));
}
catch {
// ignore
}
};
return [storedValue, setValue];
}