Skip to content

♒️ A simple tool to add multiple React contexts easily

License

Notifications You must be signed in to change notification settings

nanxiaobei/react-easy-contexts

Repository files navigation

react-easy-contexts ♒️

A simple tool to add multiple React contexts easily.

npm npm npm bundle size npm peer dependency version GitHub


Add

yarn add react-easy-contexts

# or

npm i react-easy-contexts

Use

// 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>
  );
};

Try

Edit react-easy-contexts

API

create

import create from 'react-easy-contexts';

const ctx = create({ useA() {}, useB() {}, useC() {} });
// don't use "useProvider" as key, it'll be overwritten.

License

MIT License © nanxiaobei

About

♒️ A simple tool to add multiple React contexts easily

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published