Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions hooks/useLocalStorageState.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { useEffect, useState } from 'react';

export default function useLocalStorageState(key, defaultVa1ue) {
const [state, setState] = useState(() => {
let value;
try {
value = JSON.parse(window.localStorage.getItem(key) || String(defaultVa1ue))
}
catch (e) {
value = defaultVa1ue;
}
return value;
})
useEffect(
() => {
window.localStorage.setItem(key, state);
}, [state]);
return [state, setState];
}
// export default function Counter() {
// const [count, setcount] = useLocalStorageState("my-app-count", 0)
// return (
// <div>
// <button onClick={() => setcount(count + 1)} >{count}</button>
// </div>
// )
// }