I made a simple todo app in React with hooks. I created a context file and imported it into the main App component and I created a reducer file and imported it too into the main App. I now want to make the state(the items commig from the context file) getting saved into the localState and then loaded back into the app everytime I reload the browser.
I have created a custom hook, after doing some research but I still couldn't figure out how to solve the problem. The code is shown below.
function usePersistedState(key, defaultVal) {
const [myState, setMyState] = useState(() => {
return localStorage.getItem(key) || defaultVal;
});
useEffect(() => {
localStorage.setItem(key, JSON.stringify(myState));
}, [key, myState]);
return [myState, setMyState];
}
Codesandbox project
I want to use the hook that I have already created to handle the localStorage of my app's state.