Julio Hintze
Julio Hintze

Reputation: 138

export + import object vs context

I've tried to search for an answer, but I didn't found one. Maybe I don't know the keywords.

In react, in order to give a component access to a certain value anywhere in your app, we usually use createContext + Provider + useContext.

I've read too that we can skip the Provider step, passing the createContext a value.

My questions are:

  1. If we skip the Provider step like mentioned above, we couldn't change the value of the context, right?
  2. In the case that I want a value that would NEVER change to be accessible by all components, couldn't I just make a file and export the value, making the value importable by the components, without using React Context/Props? If so, is it a bad practice?

Upvotes: 4

Views: 1086

Answers (2)

Laode Muhammad Al Fatih
Laode Muhammad Al Fatih

Reputation: 4610

Don't use context if the data you want to use is statically and globally (like environment variable).

Use context if:

  • Data is only available in several component scopes.
  • or Distributed data can be changed at any time, so all of these data consumer must know if the data has been changed (reactive).

For example like the value of the theme, it can be dark or light. The user can change the page to light or dark whenever he wants. In this case the context is very useful.

Upvotes: 6

Nafeo Alam
Nafeo Alam

Reputation: 4692

Your 2nd point won't solve the state change issue. So, even after the update, your particular variable's value will remain the same, thus, won't make any difference.

Upvotes: 0

Related Questions