简体   繁体   中英

How to store initial toggle state in localStorage using React hooks

I'm trying to store the state of a toggle in local storage, as an example of having a modal or something similar persist on refresh.

I've got this working for the most part, on first page load the boolean is just set to null, which doesn't render the <p>I'm toggled</p> tag, and when you toggle on and off, the state is stored in local storage that I can see from my 'Application Local Storage' tab in dev tools.

The problem I'm having is that on that initial page load, if you refresh the page again, the <p>I'm toggled</p> tag is shown by default.. along with every refresh after that. The toggling still works, but any refresh would return the shown state by default—which it shouldn't.

Could anybody help me understand why this is happening? I've tried several variations and can't seem to work it out.

import React from 'react';
import ReactDOM from 'react-dom';

const App = () => {
  const [toggle, setToggle] = React.useState(localStorage.getItem('toggle'))

  React.useEffect(() => {
    localStorage.setItem('toggle', toggle)
  }, [toggle]);

  return (
    <div>
        <button onClick={() => {
            setToggle(!toggle)
        }}>
            Toggle
        </button>
        {toggle ? <p>I'm toggled</p> : null}
    </div>
  );
};

export default App;

ReactDOM.render(<App />, document.getElementById('root'));

That's because local storage stores your state as a string. So when you toggle the state it's being changed to "true" or "false" during the save to the storage. So once you refresh the page you are checking against.toggle, Now, at that time the toggle === "false" and the !"false" is equal to true .

One of the solutions would be to check if the stored value is "true" :

const [toggle, setToggle] = React.useState(localStorage.getItem('toggle') === "true")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM