Local storage not updating first time with useState

Issue

This Content is from Stack Overflow. Question asked by flinch85

Why doesn’t the local storage change happen on first click?

const Menu = () => {
  const { auth, setAuth } = useContext(AuthContext);

  useEffect(() => {
    localStorage.setItem("theme", auth.theme);
  }, [auth.theme]);

  return (
    <header>
        <ToggleSwitch
          defaultChecked={auth.theme}
          onChange={() => {
            setAuth((prevState) => ({
              ...prevState,
              theme: !prevState.theme,
            }));
          }}
        />
    </header>
  );
};

I have seen the same question asked for setState and the answer seems to be useEffect and ...prevState which I’ve done.

Edit: It in fact updates from true to false first time but not the other way around/=.



Solution

Check the Answers

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?