Added use local storage hook (#36)

This commit is contained in:
Sean 2022-10-20 19:00:35 +08:00 committed by GitHub
parent 6b68857b81
commit 3c3c9a6026
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -0,0 +1,22 @@
import { useState, useEffect } from 'react';
export default function useLocalStorage(key, defaultValue) {
const [value, setValue] = useState(() => {
try {
const saved = localStorage.getItem(key);
if (saved !== null) {
return JSON.parse(saved);
}
return defaultValue;
} catch {
return defaultValue;
}
});
useEffect(() => {
const rawValue = JSON.stringify(value);
localStorage.setItem(key, rawValue);
}, [key, value]);
return [value, setValue];
}