Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LS custom hook 🪝 #62

Open
alternadiva opened this issue Jul 22, 2022 · 0 comments
Open

LS custom hook 🪝 #62

alternadiva opened this issue Jul 22, 2022 · 0 comments

Comments

@alternadiva
Copy link

export default function useLocalStorageState(key, initial) {
if (typeof window !== "undefined") {
// Try and get some values from localStorage:
// Set up defaults if there's nothing in localStorage (i.e. the values are null):
const [value, setValue] = useState(() => {
return JSON.parse(window.localStorage.getItem(key)) || initial;
});
// localStorage is a side-effect: keep track of these
useEffect(() => {
window.localStorage.setItem(key, JSON.stringify(value));
}, [value]);
return [value, setValue];
}
}

Nice to see that you're using a custom hook to access the local storage. Such a good idea! 📦 🤩

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

No branches or pull requests

1 participant