[英]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.我正在构建一个 web 应用程序,该应用程序需要将 state 的几部分存储在上下文中,因为它们在全球范围内都是必需的。 For this, I am using the React Context API (instead of Redux).
为此,我使用 React Context API(而不是 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.).我有一个存储文件夹,它是我的组件文件夹的同级文件夹,其中我目前有一个文件存储我登录的
loggedIn
我现在在 position,我想在其中添加额外的上下文元素(当前语言、用户 XP 等) .
What is the best practice for storing these elements?存储这些元素的最佳做法是什么?
loggedIn
state and utilise the same provider, using a reducer to selectively update the state.loggedIn
相同的文件(最好是相同的对象)中,并使用相同的提供程序,使用缩减程序有选择地更新 state。 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 ) (如果这不是 Stack Overflow 的合适问题,请告诉我,我会删除它)
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.
因此,如果您有一个单一的整体上下文,其值很大 object,那么更改 object 的一部分将强制重新渲染只关心 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.
如果较小的上下文值发生变化,那么该上下文的消费者仍将需要重新呈现,但这可能是需要的,因为这些组件很可能会关心更改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.