<div class="container"></div>
const {   createContext,
  Dispatch,
  SetStateAction,
  useContext,
  useEffect,
  useRef,
  useState, } = React;

type ValueType = {
  [key: string]: Dispatch<SetStateAction<number | undefined>>;
};

const context = createContext<ValueType>(undefined as never);

const Component = ({ name }: { name: string }) => {
  console.log(name);
  const [value, setValue] = useState<number>();
  const dispatches = useContext(context);
  useEffect(() => {
    dispatches[name] = setValue;
    return () => {
      delete dispatches[name];
    };
  }, [name]);
  return (
    <div>
      {name}:{value}
    </div>
  );
};

const Page = () => {
  console.log("Main");
  const dispatches = useRef<ValueType>({}).current;
  return (
    <>
      <button onClick={() => dispatches["A"]?.((v) => (v || 0) + 1)}>A</button>
      <button onClick={() => dispatches["B"]?.((v) => (v || 0) + 1)}>B</button>
      <button onClick={() => dispatches["C"]?.((v) => (v || 0) + 1)}>C</button>
      <context.Provider value={dispatches}>
        <Component name="A" />
        <Component name="B" />
        <Component name="C" />
      </context.Provider>
    </>
  );
};

ReactDOM.render(<Page />, document.querySelector(".container"));
View Compiled

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

  1. https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js
  2. https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js
  3. https://cdn.skypack.dev/@types/[email protected]