DEV Community

Cover image for Compose multiple React providers
Mateus V. Farias
Mateus V. Farias

Posted on

4

Compose multiple React providers

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>
    );
};
Enter fullscreen mode Exit fullscreen mode

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>
    );
};
Enter fullscreen mode Exit fullscreen mode

The providers can be composed together by using the reduce function:

const compose = (providers) =>
    providers.reduce((Prev, Curr) => ({ children }) => (
        <Prev>
            <Curr>{children}</Curr>
        </Prev>
    ));
Enter fullscreen mode Exit fullscreen mode

The provider declarations in the root can be shorten below:

const Provider = compose([
    Router,
    AuthProvider,
    ThemeProvider,
    LocalizationProvider,
]);

const App = () => {
    return (
        <Provider>
            {...}
        </Provider>
    );
};
Enter fullscreen mode Exit fullscreen mode

I hope it is helpful for you.

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)