@ascodelife/react-context-provider-composer
v1.3.0
Published
Compose your react context provider to solve nested hell
Downloads
129
Maintainers
Readme
English | 简体中文
react-context-provider-composer
Compose your react context provider to solve nested hell.
github
npm package
🤔Why We Need It
When we have multiple context providers, we nest them at multiple levels, which will make the code structure more and more ugly and difficult to maintain. Therefore, I convert this multi-layer nesting into a one-dimensional array to call.
The following is a bad case.
<LoadingContext.Provider value={{ loading, setLoading }}>
<UserDataContext.Provider value={{ name: "ascodelife", age: 25 }}>
<ThemeContext.Provider value={"light"}>
{/* ....more Providers as long as you want */}
</ThemeContext.Provider>
</UserDataContext.Provider>
</LoadingContext.Provider>
📦 Install
yarn add @ascodelife/react-context-provider-composer
🔨 Usage
import ContextComposer from "@ascodelife/react-context-provider-composer";
🌰 Usage Examples
This example will show how to use it simply.
const App = () => {
return (
<ContextComposer
contexts={[
<LoadingContext.Provider value={{ loading, setLoading }} />,
<UserDataContext.Provider value={{ name: "ascodelife", age: 25 }} />,
<ThemeContext.Provider value={"light"} />,
]}
>
{ children }
</ContextComposer>
);
};
Or you can try the the following demo.
cd demo
yarn
yarn start
📚 Related article
I'm sorry it's written in Chinese.
我是如何一步步封装一个React Context Composer