Skip to content

Instantly share code, notes, and snippets.

@iam-rohid
Created August 1, 2022 05:06
Show Gist options
  • Save iam-rohid/a80c5f0cfe7155fcbe6425718e896ebf to your computer and use it in GitHub Desktop.
Save iam-rohid/a80c5f0cfe7155fcbe6425718e896ebf to your computer and use it in GitHub Desktop.
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