Ben
Ben

Reputation: 493

Should unrelated context be stored separately when using the React Context API?

I am building a web app that requires several pieces of state to be stored in context as they are required globally. For this, I am using the React Context API (instead of Redux).

I have a store folder that is a sibling to my components folder, within which I currently have one file storing my loggedIn state. I am now in the position where I want to add additional elements of context (current language, user XP etc.).

What is the best practice for storing these elements?

What are the advantages and drawbacks of each approach?

(If this is not an appropriate question for Stack Overflow, let me know and I'll delete it)

Upvotes: 2

Views: 1838

Answers (1)

Nicholas Tower
Nicholas Tower

Reputation: 84922

Keep in mind that any time the value of a context changes, every component that consumes that context must rerender. So if you have a single monolithic context, with a large object as its value, then changes to one part of the object will force rerenders of components that only care about different parts of the object.

For that reason, having a single context can be a performance problem. One way to mitigate this is to split it up into smaller contexts, each focused on a single area. If that smaller context value changes, then the consumers of that context will still need to rerender, but that's probably desired since those components are very likely to care about the change.

Upvotes: 3

Related Questions