Skip to content

Why React Context state updates are not causing re-render when updating nested objects? #162574

Closed Answered by Jatin083
JK083 asked this question in Programming Help
Discussion options

You must be logged in to vote

Yes, this issue happens due to how React detects state updates.
React re-renders a component only when it sees that the state reference has changed.
In your example, you are mutating the object directly:

contextState.user.name = "New Name";
setContextState(contextState);

Since contextState reference remains the same, React doesn't realize that anything has changed.

✅ Instead, you should always create a new object using immutable updates:

setContextState(prevState => ({
  ...prevState,
  user: {
    ...prevState.user,
    name: "New Name"
  }
}));

This way, you're creating a brand new object and React properly triggers a re-render.

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by JK083
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Programming Help Discussions around programming languages, open source and software development
2 participants