Reputation: 1224
im not fully sure i understand context but..
i was wondering if it might be possible to share several variables (colors, gutter width etc) across a project using it? to save importing them multiple times into individual files?
how would one go about this if its an appropriate use of context?
examples: variables.js
export const primary = 'blue';
export const gutter = 10;
ideally i would like it just to work so the variables could be used on the fly
container: {
paddingHorizontal: gutter,
backgroundColor: primary
}
it's for a react native project.
Upvotes: 0
Views: 1173
Reputation: 5215
The aim of context
is, indeed, sharing global data between all of your components. But relying on global data is usually not a good idea. If your React components depend on the presence of certain "globals", it makes them less self contained, and more difficult to reuse.
The React framework authors themselves discourage the use of context
, as it is usually results in anti-patterns. The main use case of context
is not to inject global variables into your components, but to connect them to globally available data sources and action dispatchers. Redux
and React-Redux
offer a very beautiful abstraction over context
, you should check those libraries out.
The basic concept is to create self-contained, standalone components that do not rely on anything but their own props
- and then wrap them into "connected wrapper components" that use context to connect those props to the a shared application state and action creators.
In this case, every single one of your components that require gutter
for their rendering would expose a gutter
prop in their API - and then you would create connected components that automatically fetch gutter
from the shared state.
See the Redux documentation for a detailed description.
Upvotes: 1