qol-hooks
Version:
A collection of React hooks to improve the quality of life of developers.
40 lines (39 loc) • 1.28 kB
JavaScript
import { useState } from "react";
/**
* @description A hook to store or get a value in localStorage
*
* @param {string} key The key to store the value in localStorage
* @param {string} initialValue The initial value to store in localStorage
* @returns {[string, (value: string) => void]} A tuple containing the stored value and a function to set the value
*
* @example```tsx
* const [value, setValue] = useLocalStorage
*
* setValue("Hello, World!");
* console.log(value); // Hello, World!
* ```
*/
function useLocalStorage(key, initialValue) {
const [storedValue, setStoredValue] = useState(() => {
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
}
catch (error) {
console.error(error);
return initialValue;
}
});
const setValue = (value) => {
try {
const valueToStore = value instanceof Function ? value(storedValue) : value;
setStoredValue(valueToStore);
window.localStorage.setItem(key, JSON.stringify(valueToStore));
}
catch (error) {
console.error(error);
}
};
return [storedValue, setValue];
}
export default useLocalStorage;