Local storage not updating first time with useState


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 (
          onChange={() => {
            setAuth((prevState) => ({
              theme: !prevState.theme,

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/=.


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?