Skip to content

Instantly share code, notes, and snippets.

@deeamtee
Created December 2, 2023 22:29
Show Gist options
  • Save deeamtee/16b7848fa130de33a63933a705947143 to your computer and use it in GitHub Desktop.
Save deeamtee/16b7848fa130de33a63933a705947143 to your computer and use it in GitHub Desktop.
import { useState, useEffect, Dispatch, SetStateAction } from 'react'
function isDefined (storedValue: string | null): boolean {
return storedValue !== null && storedValue !== 'undefined';
}
export function useLocalStorageState<T>(
key: string,
initialValue: T
): [T, Dispatch<SetStateAction<T>>] {
const [state, setState] = useState<T>(() => {
const storedValue = localStorage.getItem(key)
return isDefined(storedValue) ? (JSON.parse(storedValue!) as T) : initialValue
})
useEffect(() => {
localStorage.setItem(key, JSON.stringify(state))
}, [key, state])
return [state, setState]
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment