React component to organize and flatten providers.
npm install --save react-flat-providers
Just use the FlatProviders
-Component and pass it an Array of your Providers and their Props:
import { FlatProviders } from 'react-flat-providers';
// ...
<FlatProviders
providers={[
ProviderWithoutProps,
[ProviderWithProps, { providerProps: 'propsValue' }],
]}
>
<App />
</FlatProviders>
If you are using TypeScript
and you want type-safety for your Providers' props, you can use the provided makeProvider
function or useChainProviders
hook:
import { FlatProviders, makeProvider } from 'react-flat-providers';
<FlatProviders
providers={[
makeProvider(ProviderWithProps, { providerProps: 'typeSafe'}),
]}
>
import { useChainProviders } from 'react-flat-providers';
const FlatChainedProviders = useChainProviders()
.add(NumberProvider)
.add(BooleanProvider, { initialValue: true })
.make();
<FlatChainedProviders>
<App />
</FlatChainedProviders>
A full working example can be found following the link below:
https://stackblitz.com/edit/react-flat-providers-example
/**
* Its very common to have Spaceships like this in your React project.
* A common pattern is to break these big Spaceships into smaller ones.
* But I saw that this increases the amount of code and complexity even more.
*/
<NumberProvider>
<BooleanProvider>
<StringProvider>
...
<ContextConsumingComponent />
...
</StringProvider>
</BooleanProvider>
</NumberProvider>
MIT © sincovschi