Created
February 7, 2023 13:27
-
-
Save adeleke5140/c2d687a7f2c3ba916f1098da7dd11172 to your computer and use it in GitHub Desktop.
a hook to useLocalStorage in NextJS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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