Created
May 22, 2024 04:45
-
-
Save thepuskar/5e855236c9a7cee0731358ee06d01abf to your computer and use it in GitHub Desktop.
No More React Context Hell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment