Skip to content

Instantly share code, notes, and snippets.

@netojose
Forked from sciotta/ComposeProviders.tsx
Last active September 13, 2022 01:27
Show Gist options
  • Save netojose/256b1e9fbfffb7eaa9332b682a401bb1 to your computer and use it in GitHub Desktop.
Save netojose/256b1e9fbfffb7eaa9332b682a401bb1 to your computer and use it in GitHub Desktop.
Compose React Providers to avoid too much chaining

Too gist is too resolve problem of chaining of many context providers

  <AuthProvider>
    <ThemeProvider>
        <LionessProvider>
            <ErrorProvider>
              <LoadingProvider>
                <Component />
              </LoadingProvider>
            </ErrorProvider>
        </LionessProvider>
    </ThemeProvider>
  </AuthProvider>

Solution

  <ComposeProviders
    with=[
       { component: AuthProvider },
       {  
         component: ThemeProvider,
         props: { 
           theme: { main: 'palevioletred' }
         }
       },
       { component: LionessProvider },
       { component: ErrorProvider },
       { component: LoadingProvider }
    ]
  >
    <Component />
  </ComposeProviders>
import React, { ElementType, ReactNode, ReactElement } from 'react'
interface ComposeProvidersProps {
with: Array<{
component: ElementType,
props?: Record<string, unknown>,
}>,
children: ReactNode,
}
const ComposeProviders = ({
with: Providers,
children,
}: ComposeProvidersProps): ReactElement => (
<>
{Providers.reduce(
(accProviders, Provider) => (
<Provider.component {...Provider.props}>{accProviders}</Provider.component>
),
children,
)}
</>
)
export default ComposeProviders;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment