Skip to content

Instantly share code, notes, and snippets.

@adeleke5140
Created February 7, 2023 13:27
Show Gist options
  • Select an option

  • Save adeleke5140/c2d687a7f2c3ba916f1098da7dd11172 to your computer and use it in GitHub Desktop.

Select an option

Save adeleke5140/c2d687a7f2c3ba916f1098da7dd11172 to your computer and use it in GitHub Desktop.
a hook to useLocalStorage in NextJS
import { useState, useEffect } from "react";
const useLocalStorage = (key: string, initialValue: any) => {
const isServer = typeof window === "undefined";
const [value, setValue] = useState(() => {
if (isServer) {
return initialValue;
}
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
console.error(error);
return initialValue;
}
});
useEffect(() => {
if (isServer) {
return;
}
try {
window.localStorage.setItem(key, JSON.stringify(value));
} catch (error) {
console.error(error);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [value, key]);
return [value, setValue];
};
export default useLocalStorage;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment