Skip to content

Instantly share code, notes, and snippets.

@Luisgustavom1
Last active December 27, 2022 19:10
Show Gist options
  • Save Luisgustavom1/ca4c736a8d329130d184a330b05cc9f6 to your computer and use it in GitHub Desktop.
Save Luisgustavom1/ca4c736a8d329130d184a330b05cc9f6 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=[
       AuthProvider,
       ThemeProvider,
       LionessProvider,
       ErrorProvider,
       LoadingProvider
    ]
  >
    <Component />
  </ComposeProviders>
import React from 'react'
interface IComposeProvidersProps {
with: Array<React.ElementType>
children: React.ReactNode
}
export const ComposeProviders = ({
with: Providers,
children,
}: IComposeProvidersProps) => {
return (
<React.Fragment>
{Providers.reduce(
(AccProviders, Provider) => (
<Provider>{AccProviders}</Provider>
),
children,
)}
</React.Fragment>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment