refactor: Create useLocalStorage hook to reduce code duplication

This commit is contained in:
SyedaAnshrahGillani
2025-10-01 17:16:09 +05:00
parent 2a5d27ffc0
commit 2d6c3b5755
2 changed files with 37 additions and 32 deletions

View File

@@ -0,0 +1,28 @@
import { useState } from 'react';
function useLocalStorage(key, initialValue) {
const [storedValue, setStoredValue] = useState(() => {
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
console.log(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.log(error);
}
};
return [storedValue, setValue];
}
export default useLocalStorage;