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

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay