Skip to content

Instantly share code, notes, and snippets.

@highlander08
Forked from fedek6/useLocalStorage.ts
Created April 12, 2023 13:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save highlander08/ec9e8cfe86fba0a66ab419f162f22c08 to your computer and use it in GitHub Desktop.
Save highlander08/ec9e8cfe86fba0a66ab419f162f22c08 to your computer and use it in GitHub Desktop.
Working useLocalStorage hook for Next.js (no warnings in console)
/* eslint-disable no-console */
/* eslint-disable react-hooks/exhaustive-deps */
import { useState, useEffect } from "react";
export const useLocalStorage = <T>(key: string, initialValue: T) => {
const [storedValue, setStoredValue] = useState<T | undefined>();
const setValue = (value: T) => {
window.localStorage.setItem(key, JSON.stringify(value));
};
useEffect(() => {
const value = window.localStorage.getItem(key);
if (value) {
try {
const parsed = JSON.parse(value) as T;
setStoredValue(parsed);
} catch (error) {
console.log(error);
setStoredValue(initialValue);
}
} else {
setStoredValue(initialValue);
}
}, []);
useEffect(() => {
if (storedValue) {
setValue(storedValue);
}
}, [storedValue]);
return [storedValue as T, setStoredValue] as const;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment