简体   繁体   English

对所有屏幕应用 React Context API 有多好

[英]How good is to apply React Context API for all screens

Currently I have four contexts that wrap all my routes (as shown bellow) so that I don't have lost providers all around my app screens and components.目前我有四个上下文来包装我的所有路由(如下所示),这样我的应用程序屏幕和组件周围就不会丢失提供程序。 As far as I know, when I modify the value of a context variable, every component that uses it will update too, what can lead to memory problems, but my question is: if my providers, that wrap all routes/screens, even the ones that uses no context variable, may cause the same memory related problems.据我所知,当我修改上下文变量的值时,使用它的每个组件也会更新,这会导致 memory 问题,但我的问题是:如果我的提供程序,它包含所有路由/屏幕,甚至那些不使用上下文变量的,可能会导致相同的 memory 相关问题。

 <AuthProvider>
  <SelectedBranchProvider>
    <SelectedEventProvider>
      <DrawerFormProvider>
        <RightDrawerNavigator />
      </DrawerFormProvider>
    </SelectedEventProvider>
  </SelectedBranchProvider>
</AuthProvider>

The danger with context isn't memory issues, it's unneeded re-renders.上下文的危险不是 memory 问题,而是不需要的重新渲染。 The way Context is implemented defeats some of React's diffing, so a change in Context can cause a re-render in any component that uses the same Context, even if the value that changes is unused in the component. Context 的实现方式克服了 React 的一些差异,因此 Context 的更改可能会导致使用相同 Context 的任何组件重新渲染,即使更改的值在组件中未使用也是如此。

If you have a small app, or only rarely change what's in your context, you'll probably never hit these limitations.如果您有一个小型应用程序,或者很少更改您的上下文中的内容,那么您可能永远不会遇到这些限制。 Good use cases for context are things that would require many re-renders and rarely change, like user language or app theme.良好的上下文用例是需要多次重新渲染并且很少更改的东西,例如用户语言或应用程序主题。

The docs for Context have a caveats section that goes over this: https://reactjs.org/docs/context.html#caveats Context 的文档有一个警告部分: https://reactjs.org/docs/context.html#caveats

Here's a blog post with a good example of how this can cause re-renders:https://blog.logrocket.com/pitfalls-of-overusing-react-context/这是一篇博客文章,其中有一个很好的例子说明这如何导致重新渲染:https://blog.logrocket.com/pitfalls-of-overusing-react-context/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM