Home > Enterprise >  What is the difference between react usecontext and global variables
What is the difference between react usecontext and global variables

Time:04-28

The function of react context is to facilitate the component to pass values, but it is not responsive. It needs to cooperate with usestate to achieve responsiveness. What's the difference between using global variables and setting a layer of usestate can also achieve the effect of component transparent transmission. I can think of the difference between context and global variables is that context only transmits data to wrapped components, while global variables have no such restriction

CodePudding user response:

props and context are the ways that react has for moving data between components. Built into these are the fact that if you rerender the source component and it has a new value for the prop/context, then the destination component will rerender too. The child component does not need to somehow register an event listener on the props/context, and then set state when the value changes; it's enough that the props/context changed.

If you do a global variable, then yes, it can in principle be available to all components. However, you will need to write code which listens to changes in that global variable (for example, with an event emitter or an observable), and then every component that consumes it will need to set local state when the global value changes, in order to rerender itself.

context only transmits data to wrapped components, while global variables have no such restriction

While you describe this as a restriction, it's sometimes a very useful benefit. For example, suppose you have a Theme object that sets the colors for your app. It's provided via context, and your ui components use it to style themselves.

But you also want to let the user change the theme, and see a preview of the change. Since the Theme is using context, you can create a new context provider that just wraps around the preview part of your app. Components inside the preview will use the modified theme, while the rest of the app behaves as normal.

  • Related