the custom hook 'useSemiPersistenceState' is implemented outside the App component including the useEffect hook
const useSemiPersistentState = (key, initialState) => {
const [value, setValue] = React.useState(localStorage.getItem(key) || initialState);
React.useEffect(
() => {
localStorage.setItem(key, value);
},
[value, key],
);
return [value, setValue];
};
the custom hook is executed only once when the App component is mounted for the first time , so how the local storage set the new value of SearchTerm (from input field) when it gets updated by the setSearchTerm ?
const App = () => {
const [searchTerm, setSearchTerm] = useSemiPersistentState('search', 'React');
const handleSeach = (event) => {
setSearchTerm(event.target.value);
};
...
}
When the component loads for the first time, initial state is passed in the 'value' variable and the same is stored in the local storage also. The 'value here is basically the search keyword you are going to use so when in the second snippet the usePersistentState() is called its initial value is set to 'react'. But also at the same line is an example of array destructuring. So when setSearchTerm is called snippet 2, the 'value' variable gets updated in usePersistentState and useEffect is triggered as it gets triggered if 'value' variable changes and same gets update in local storage.
In short, the 'value' variable is searchTerm when usePersistentState is called or triggered and hence the whole flow is working on that premise.