Skip to content

Instantly share code, notes, and snippets.

@SheryConcepts
Last active June 9, 2023 08:00
Show Gist options
  • Save SheryConcepts/36e2042e2c1d955c2aafbc18db3e63db to your computer and use it in GitHub Desktop.
Save SheryConcepts/36e2042e2c1d955c2aafbc18db3e63db to your computer and use it in GitHub Desktop.
React hook for localStorage. Has the same interface as useState.
import { useEffect, useState } from "react";
export function useLocalStorage<T>(key: string, initialValue: T) {
const [state, setState] = useState<T>(() => {
const json = localStorage.getItem(key);
return json ? JSON.parse(json) : initialValue;
});
// a wrapper over setState, but it also save given value to localStorage
function setStorage(value: T | ((v: T) => T)) {
const data = value instanceof Function ? value(state) : value;
const json = JSON.stringify(data);
localStorage.setItem(key, json);
setState(data);
}
return [state, setStorage] as const;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment