English | 简体中文
Compose your react context provider to solve nested hell.
github
npm package
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>
yarn add @ascodelife/react-context-provider-composer
import ContextComposer from "@ascodelife/react-context-provider-composer";
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
I'm sorry it's written in Chinese.
我是如何一步步封装一个React Context Composer