Skip to content

Instantly share code, notes, and snippets.

@jharris711
Created March 7, 2023 21:35
useLocalStorage React hook
import { useState, useEffect } from "react";
export function useLocalStorage<T>(
key: string,
initialValue: T
): [T, (value: T) => void] {
const [value, setValue] = useState<T>(() => {
const storedValue = localStorage.getItem(key);
return storedValue !== null ? JSON.parse(storedValue) : initialValue;
});
useEffect(() => {
localStorage.setItem(key, JSON.stringify(value));
}, [key, value]);
const updateValue = (newValue: T) => setValue(newValue);
return [value, updateValue];
}
@LubaGmail
Copy link

Helpful hook. Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment