It is difficult for me to understand this custom React hook. The code works, but I understand only some parts. It is a useLocalStorage hook. I will be grateful for any feedback.
This is my App.js file.
import "./App.css";
import useLocalStorage from "./useLocalStorage";
function App() {
const [name, setName] = useLocalStorage("NAME", "");
return (
<>
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
/>
<div>My name is {name}</div>
</>
);
}
export default App;
This is my useLocalStorage.js file.
import { useEffect, useState } from "react";
function getSavedValue(key, initialValue) {
const savedValue = JSON.parse(localStorage.getItem(key));
if (savedValue) return savedValue;
return initialValue;
}
function useLocalStorage(key, initialValue) {
console.log(key);
console.log(initialValue);
const [value, setValue] = useState(() => {
return getSavedValue(key, initialValue);
});
useEffect(() => {
localStorage.setItem(key, JSON.stringify(value));
});
return [value, setValue];
}
export default useLocalStorage;
I understand how the savedValue (in useLocalStorage.js) is passed to the App.js file. I just retrieve it with the getSavedValue function, like this.
const [value, setValue] = useState(() => {
return getSavedValue(key, initialValue);
});
And later, I pass it to the App.js with these two lines.
Firstly, I return the value in the useLocalStorage.js
return [value, setValue];
Secondly, I pass the value variable into the name variable in the App.js file.
const [name, setName] = useLocalStorage("NAME", "");
This is how the passing of the savedValue from useLocalStorage.js to App.js works. I think.
But how does it work the other way around? How is the updated name variable passed from App.js to useLocalStorage? It seems to me that only “NAME” and initialValue are passed from App.js to useLocalStorage.js. Like this.
const [name, setName] = useLocalStorage("NAME", "");
As a result, in the useLocalStorage.js, I am able to access the “NAME” and intitialValue(“”) with the console.log statement.
console.log(key);
console.log(initialValue);
And it works. But I do not have this option for the updated name variable. Or do I? How do I access the updated name variable (available in the App.js) in the useLocalStorage.js???