Skip to content

scottjr632/react-provider-wrapper

Repository files navigation

NPM version NPM downloads npm-publish

About

react-provider-wrapper wraps your application in all your React context providers. This solves the issue of wrapper hell that can happen when working with multiple providers for an application or section of an application that needs to become a consumer.

Example of wrapper hell

const App = () => (
    <FirstProvider>
      <SecondProvider>
        <ThirdProvider>
          <FourthProvider>
            <FifthProvider>
              <FirstConsumer />
              <SecondConsumer />
            </FifthProvider>
          </FourthProvider>
        </ThirdProvider>
      </SecondProvider>
    </FirstProvider>
)

Installing

npm

$ npm install react-provider-wrapper

yarn

$ yarn add react-provider-wrapper

Getting started

Import WrapProviders and each of the providers into the component that you want to be the parent component of the children that you want to consume from the provider.

import WrapProviders from 'react-provider-wrapper'
import MockContextProvider from './mockContextProvider.tsx'
import MockSecondContextProvider from './mockSecondContextProvider.tsx'

Example provider

import React, { createContext, useState, useContext } from 'react'

const ProviderMockContext = createContext(null)
const MockContextProvider = ({ children }) => {
  const [state, setState] = useState({});
  return (
    <ProviderMockContext.Provider value={{state, setState}}>
      {children}
    </ProviderMockContext.Provider>
  )
}

export const useProviderMock = () => useContext(ProviderMockContext)
export default MockContextProvider

Create array of providers

const providers = [
    MockContextProvider,
    MockSecondContextProvider
]

This can also be refactored out into a module that contains all providers and exports them in an index.{ts,js} file.

Wrap application or parent component with WrapProviders

    const App = () => (
        <WrapProviders providers={providers}>
            <ConsumerComponent />
            <AnotherConsumerComponent />
        </WrapProviders>
    )

About

Wrap React application with multiple providers. Avoiding wrapper hell created by multiple providers.

Topics

Resources

Stars

Watchers

Forks

Packages

No packages published