Home > Enterprise >  How to set the current state to the useState hook?
How to set the current state to the useState hook?

Time:11-18

I have a state to keep track when a SubMenu is opened, and toggle it when another Menu Item is clicked. It goes like this:

    const [open, setOpen] = useState();
    const toggle = (id) => setOpen(id);

    onClick={() => toggle(item.navId)}

When I click the refresh button in the browser, the current Sub Menu that is opened, closes. I believe it is because the initial state is empty. How can I keep the current Sub Menu opened after the page is reloaded/refreshed. I've been looking around and I am really not sure if I should use prevState or how to implement it to my case. Any tips or pointing a direction to a solution is much appreciated. Thanks.

CodePudding user response:

You could add a query parameter for the opened sub menu. URL might look something like this: www.test.com/menu?nav=1. Then you could read the value of nav and use that for the initial state.

CodePudding user response:

When you hit the refresh button of the browser, your state will take its initial value, null in your case because you are not passing anything. prevState will have the same behaviour. localStorage can be a solution.

  • Related