Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between react usecontext and global variables

Tags:

reactjs

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

like image 239
shuisheng Avatar asked Jun 21 '26 15:06

shuisheng


1 Answers

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 are making a group of components that need to work together, such as a TabContainer and a TabPanel. They need to share data between themselves. Since context is only available to the wrapped components, the TabContainer can render a context provider, and the TabPanels can access that context. And if there are multiple TabContainers on the page, they won't interfere with eachother.

Or as another 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.

In short: you can put your context provider at whatever level makes sense for your needs. If you want it to be global, put it at the top of your component tree and it's global. But if you want something confined to a region, you can do that too. A global variable does not have this flexibility.

like image 188
Nicholas Tower Avatar answered Jun 26 '26 07:06

Nicholas Tower