简体   繁体   中英

What is different between React Context API and a separate JS file to store user data?

I am new in ReactJs. As I understand React context API used for sharing data between components to avoid pass data with props repeatedly in nested components. But I can do it with a simple separate JS file. In a JS file I can simply declare an object to keep data and have some functions to update or get the stored data in all components.

What is the main difference between Context API and a JS file to store user data? Where and when should I use React Context API?

React is aware of the context and components that consume the context will re-render if the context changes.

If you change a value in a JS module, React will not update the component tree.

The main and most important difference is that React will re-render all consumer components of a context provider. To quote the documentation :

All consumers that are descendants of a Provider will re-render whenever the Provider's value prop changes. The propagation from Provider to its descendant consumers (including .contextType and useContext ) is not subject to the shouldComponentUpdate method, so the consumer is updated even when an ancestor component skips an update.

So as a rule of thumb. Use the React Context API when the "global" state influences the rendering result. (Which is 99% of the time, since React is all about rendering views.)

Another difference is that a context is not simply a single global object. Take for example the following code:

<Theme.Provider value="light">
  <MyComponent />
  <Theme.Provider value="dark">
    <MyComponent />
  </Theme.Provider>
</Theme.Provider>

Here the first MyComponent will render with the light theme, while the second MyComponent will render with the dark theme. There are multiple context values active at the same time, the nesting determines which value gets used.

There are probably a lot more differences, and I would recommend you to read the React Context documentation if you are interested in the details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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