Skip to content

Latest commit

 

History

History
69 lines (59 loc) · 1.44 KB

compose-multiple-react-providers.mdx

File metadata and controls

69 lines (59 loc) · 1.44 KB
category cover created tags title
Tip
/assets/tips/compose-react-providers.png
2021-05-13
React
Compose multiple React providers

Nowadays, it is common 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 accomplished by the 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 as below:

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

const App = () => {
    return (
        <Provider>
            {...}
        </Provider>
    );
};