A simple tool to add multiple React contexts easily.
yarn add react-easy-contexts
# or
npm i react-easy-contexts
// App.jsx
import { useState, useMemo } from 'react';
import create from 'react-easy-contexts';
export const ctx = create({
useX() {
const [x, setX] = useState(0);
return useMemo(() => ({ x, setX }), [x]);
},
useY() {
const [y, setY] = useState(0);
return useMemo(() => ({ y, setY }), [y]);
},
useZ() {
const [z, setZ] = useState(0);
return useMemo(() => ({ z, setZ }), [z]);
},
});
const App = () => {
const Provider = ctx.useProvider();
return (
<Provider>
<Main />
</Provider>
);
};
// Main.jsx
import { ctx } from './App';
const Main = () => {
const { x } = ctx.useX();
const { y } = ctx.useY();
const { z } = ctx.useZ();
return (
<div>
{x} {y} {z}
</div>
);
};
Without react-easy-contexts
, equals to:
// App.jsx
import { useState, useContext, useMemo, createContext } from 'react';
const XContext = createContext({});
const YContext = createContext({});
const ZContext = createContext({});
export const useX = () => useContext(XContext);
export const useY = () => useContext(YContext);
export const useZ = () => useContext(ZContext);
const XProvider = ({ children }) => {
const [x, setX] = useState(0);
const value = useMemo(() => ({ x, setX }), [x]);
return <XContext.Provider value={value}>{children}</XContext.Provider>;
};
const YProvider = ({ children }) => {
const [y, setY] = useState(0);
const value = useMemo(() => ({ y, setY }), [y]);
return <YContext.Provider value={value}>{children}</YContext.Provider>;
};
const ZProvider = ({ children }) => {
const [z, setZ] = useState(0);
const value = useMemo(() => ({ z, setZ }), [z]);
return <ZContext.Provider value={value}>{children}</ZContext.Provider>;
};
const App = () => {
return (
<XProvider>
<YProvider>
<ZProvider>
<Main />
</ZProvider>
</YProvider>
</XProvider>
);
};
// Main.jsx
import { useX, useY, useZ } from './App';
const Main = () => {
const { x } = useX();
const { y } = useY();
const { z } = useZ();
return (
<div>
{x} {y} {z}
</div>
);
};
import create from 'react-easy-contexts';
const ctx = create({ useA() {}, useB() {}, useC() {} });
// don't use "useProvider" as key, it'll be overwritten.