Nowadays, it is commom to use React's context at the root of an application to manage a shared state between any components.
For example, checking whether or not the current user has logged in might be a accomplished by AuthProvider
provider:
const App = () => {
return (
<AuthProvider>
{...}
</AuthProvider>
);
};
Using multiple providers could make the code harder to read because there are a lot of nested components:
const App = () => {
return (
<Router>
<AuthProvider>
<ThemeProvider>
<LocalizationProvider>
{...}
</LocalizationProvider>
</ThemeProvider>
</AuthProvider>
</Router>
);
};
The providers can be composed together by using the reduce
function:
const compose = (providers) =>
providers.reduce((Prev, Curr) => ({ children }) => (
<Prev>
<Curr>{children}</Curr>
</Prev>
));
The provider declarations in the root can be shorten below:
const Provider = compose([
Router,
AuthProvider,
ThemeProvider,
LocalizationProvider,
]);
const App = () => {
return (
<Provider>
{...}
</Provider>
);
};
I hope it is helpful for you.
Top comments (0)