No More React Context Hell

If you always wanted it to look like this

<Providers providers={[
<FooContext.Provider value=”foo” />,
<BarContext.Provider value=”bar” />,
<BazContext.Provider value=”baz” />,
]}>
<App />
</Pro…


This content originally appeared on DEV Community and was authored by Denis Maushov

If you always wanted it to look like this

  <Providers providers={[
    <FooContext.Provider value="foo" />,
    <BarContext.Provider value="bar" />,
    <BazContext.Provider value="baz" />,
  ]}>
    <App />
  </Providers>,

here is your Providers Component:

const Providers = ({providers, children}) => {
  const renderProvider = (providers, children) => {
    const [provider, ...restProviders] = providers;

    if (provider) {
      return React.cloneElement(
        provider,
        null,
        renderProvider(restProviders, children)
      )
    }

    return children;
  }

  return renderProvider(providers, children)
}

Enjoy!

Like, share and etc


This content originally appeared on DEV Community and was authored by Denis Maushov


Print Share Comment Cite Upload Translate Updates
APA

Denis Maushov | Sciencx (2021-08-28T07:59:58+00:00) No More React Context Hell. Retrieved from https://www.scien.cx/2021/08/28/no-more-react-context-hell/

MLA
" » No More React Context Hell." Denis Maushov | Sciencx - Saturday August 28, 2021, https://www.scien.cx/2021/08/28/no-more-react-context-hell/
HARVARD
Denis Maushov | Sciencx Saturday August 28, 2021 » No More React Context Hell., viewed ,<https://www.scien.cx/2021/08/28/no-more-react-context-hell/>
VANCOUVER
Denis Maushov | Sciencx - » No More React Context Hell. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/08/28/no-more-react-context-hell/
CHICAGO
" » No More React Context Hell." Denis Maushov | Sciencx - Accessed . https://www.scien.cx/2021/08/28/no-more-react-context-hell/
IEEE
" » No More React Context Hell." Denis Maushov | Sciencx [Online]. Available: https://www.scien.cx/2021/08/28/no-more-react-context-hell/. [Accessed: ]
rf:citation
» No More React Context Hell | Denis Maushov | Sciencx | https://www.scien.cx/2021/08/28/no-more-react-context-hell/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.