From c949e1dcd447b5d49a8fcff412ddcea99e5206d5 Mon Sep 17 00:00:00 2001 From: MaZ Date: Tue, 30 May 2023 15:16:41 +0200 Subject: [PATCH] add useLocalStorage --- src/util/useLocalStorage.ts | 39 +++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 src/util/useLocalStorage.ts diff --git a/src/util/useLocalStorage.ts b/src/util/useLocalStorage.ts new file mode 100644 index 00000000..9c7ee066 --- /dev/null +++ b/src/util/useLocalStorage.ts @@ -0,0 +1,39 @@ +import { useState, useEffect } from 'react'; + +/* +----------------------------------------------------------------- +To use this hook in a React component, you can call it like this: +----------------------------------------------------------------- +import { useLocalStorage } from './useLocalStorage'; + +function MyComponent() { + const [count, setCount] = useLocalStorage('count', 0); + + function handleClick() { + setCount(count + 1); + } + + return ( +
+

Count: {count}

+ +
+ ); +} +*/ + +export function useLocalStorage( + storageKey: string, + fallbackState: T, +): [T, (value: T) => void] { + const [value, setValue] = useState(() => { + const storedValue = localStorage.getItem(storageKey); + return storedValue ? JSON.parse(storedValue) : fallbackState; + }); + + useEffect(() => { + localStorage.setItem(storageKey, JSON.stringify(value)); + }, [value, storageKey]); + + return [value, setValue]; +}