Home:ALL Converter>How can I make the state persist in localStorage by using React hooks?

How can I make the state persist in localStorage by using React hooks?

Ask Time:2019-06-21T20:27:58         Author:code_dude

Json Formatter

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.

Author:code_dude,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/56703494/how-can-i-make-the-state-persist-in-localstorage-by-using-react-hooks
yy