Skip to content

Instantly share code, notes, and snippets.

@JayMGurav
Created May 2, 2021 04:08
Show Gist options
  • Save JayMGurav/3f6346be4294d75b1b3b0695b9fc5745 to your computer and use it in GitHub Desktop.
Save JayMGurav/3f6346be4294d75b1b3b0695b9fc5745 to your computer and use it in GitHub Desktop.
A custom hook to use localStorage
import { useState, useEffect } from "react";
const useLocalStorage = (initialState, key) => {
const [value, setValue] = useState(() => {
const keyValue = localStorage.getItem(key);
if(keyValue) return JSON.parse(keyValue)[value];
return initialState;
});
useEffect(() => {
localStorage.setItem(key, JSON.stringify({value});
},[value]);
return [value, setValue];
}
export default useLocalStorage;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment