Created
August 1, 2022 05:06
-
-
Save iam-rohid/a80c5f0cfe7155fcbe6425718e896ebf to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useEffect, useState } from "react"; | |
export type UseLocalStorageProps<T> = { | |
key: string; | |
value: T; | |
}; | |
export type UseLocalStorageReturn<T> = [ | |
state: T, | |
setState: (newState: T) => void | |
]; | |
export function useLocalStorage<T>({ | |
key, | |
value, | |
}: UseLocalStorageProps<T>): UseLocalStorageReturn<T> { | |
const [state, setState] = useState<T>(value); | |
useEffect(() => { | |
const lsstate = localStorage.getItem(key); | |
setState(lsstate ? JSON.parse(JSON.stringify(lsstate)) : value); | |
}, [key, value]); | |
const onStateChange = (newState: T) => { | |
setState(newState); | |
localStorage.setItem(key, JSON.parse(JSON.stringify(newState))); | |
}; | |
return [state, onStateChange]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment