From e2946569a52982a01f04bb50c07dc4c3a17d54d1 Mon Sep 17 00:00:00 2001 From: axelerant-hardik Date: Fri, 19 Jul 2024 16:35:01 +0530 Subject: [PATCH] Exercise: custom useLocalStorage hook --- src/App.jsx | 60 +++++++++++++++++++++++++++++++++++++++++- src/useLocalStorage.js | 23 ++++++++++++++++ 2 files changed, 82 insertions(+), 1 deletion(-) create mode 100644 src/useLocalStorage.js diff --git a/src/App.jsx b/src/App.jsx index 85ffc61..8656f28 100644 --- a/src/App.jsx +++ b/src/App.jsx @@ -1,5 +1,63 @@ +import { useLocalStorage } from "./useLocalStorage" + function App() { - return "Hello World" + const [firstName, setFirstName] = useLocalStorage("FIRST_NAME", "") + + // Bonus: + const [lastName, setLastName] = useLocalStorage("LAST_NAME", () => { + return "Default" + }) + + // Bonus: + const [hobbies, setHobbies] = useLocalStorage("HOBBIES", [ + "Programming", + "Weight Lifting", + ]) + + return ( + <> +
+ + setFirstName(e.target.value)} + /> +
+ +
+ + setLastName(e.target.value)} + /> +
+ +
{hobbies.join(", ")}
+ + + ) } export default App diff --git a/src/useLocalStorage.js b/src/useLocalStorage.js new file mode 100644 index 0000000..4d36254 --- /dev/null +++ b/src/useLocalStorage.js @@ -0,0 +1,23 @@ +import { useEffect, useState } from "react" + +export function useLocalStorage(key, initialValue) { + let finalValue = localStorage.getItem(key) + if (finalValue == null) { + finalValue = + typeof initialValue === "function" ? initialValue() : initialValue + } else { + finalValue = JSON.parse(finalValue) + } + + const [value, setValue] = useState(finalValue) + + useEffect(() => { + if (value != null) { + localStorage.setItem(key, JSON.stringify(value)) + } else { + localStorage.removeItem(key) + } + }, [value, key]) + + return [value, setValue] +}