Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 472
Parham.D Avatar asked Nov 07 '25 10:11

Parham.D


2 Answers

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.

like image 83
thedude Avatar answered Nov 10 '25 00:11

thedude


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.

like image 24
3limin4t0r Avatar answered Nov 10 '25 00:11

3limin4t0r



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!