Created
March 7, 2023 21:35
useLocalStorage React hook
This file contains 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 { 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]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Helpful hook. Thank you!