-1

The ThemeContext example from this link works, but it only serves one field. I tried to use this example for a complex type UserContext. The state is set, but not rendered.

I published the codesandbox example.

The first button toggled the state theme.

The second button changes the User.auth State but the page is not rendered.

You can see that the state has been set correctly when you click the first button.

Does anyone have any idea what I'm doing wrong?

Alligator
  • 250
  • 1
  • 7
  • 14
  • 1
    The code in question should be visible in your question, not just an external link. You haven't even linked to the source code, just the app from the code sandbox. See https://stackoverflow.com/help/minimal-reproducible-example – Ruan Mendes Dec 30 '20 at 00:03
  • The source code is linked (see bottom right corner). – jack.benson Dec 30 '20 at 00:10

1 Answers1

1

The problem is here:

if (aUser.authorized) {
  aUser.authorized = false;
  setUser(aUser);
} else {
  aUser.authorized = true;
  setUser(aUser);
}

You are mutating an object in your state. You shouldn't do that. React tests if it should re-render by seeing if state has the same object or not. Since you haven't passed in a new object, React doesn't know it should re-render.

You probably want this instead:

function toggleAuth() {
  setUser({ ...user, authorized: !user.authorized })
}

This way you create a new object to pass to setState, React sees that it's a new object, and then will re-render as you expect.


And the reason the Theme toggle works is that it uses this function:

function togleTheme() {
  theme === Theme.Dark ? setTheme(Theme.Light) : setTheme(Theme.Dark);
}

Which passes in a completely different value each time it toggles, without any mutations of existing objects. So React can notice that they are different and re-render.

Alex Wayne
  • 178,991
  • 47
  • 309
  • 337
  • 1
    Many many thanks. You not only showed me the solution but also described why it works. That's great. I wish you a great day and a happy new year. – Alligator Dec 30 '20 at 09:14