Search code examples
reactjsinputfrontendlocal-storagerefresh

React retains the input value after the page is refreshed and keeps it in local storage


I'm doing a feature using react, which saves text from input and automatically updates to local storage, I want even if I refresh the page the text in the input stays and the state doesn't reset from scratch. Thanks for helping me, have a nice day. please give me an the demo in the following codesandbox codesandbox link. one more time thank you very much


Solution

  • First you want to store your input's value in react state

    const [value, setValue] = useState("");
    

    When the input changes, write the change to react state, and also localStorage

    const handleChange = (e) => {
      setValue(e.target.value);
      localStorage.setItem("inputValue", e.target.value);
    };
    

    When the component is mounted, we want to set the initial state of the input to the value in localStorage

    useEffect(() => {
      setValue(localStorage.getItem("inputValue"));
    }, []);
    

    Finally, hook the handler to onChange, and use the React state as the form value

    <input
      value={value}
      onChange={handleChange}
    />
    

    See: https://codesandbox.io/s/react-input-not-reload-after-refreshing-forked-q84r8?file=/demo.js