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

type ValueType = { [key: string]: number | undefined };

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

const Component = ({ name }: { name: string }) => {
  const value = useContext(context);
  console.log(name);
  return (
    <div>
      {name}:{value[name]}
    </div>
  );
};
const Component2 = ({ name }: { name: string }) => {
  console.log(name);
  return (
    <div>
      {name}
    </div>
  );
};
const Page = () => {
  const [value, setValue] = useState<ValueType>({});
  console.log("Main");
  return (
    <>
      <button onClick={() => setValue((v) => ({ ...v, A: (v["A"] || 0) + 1 }))}>
        A
      </button>
      <button onClick={() => setValue((v) => ({ ...v, B: (v["B"] || 0) + 1 }))}>
        B
      </button>
      <button onClick={() => setValue((v) => ({ ...v, C: (v["C"] || 0) + 1 }))}>
        C
      </button>
      <context.Provider value={value}>
        <Component name="A" />
        <Component name="B" />
        <Component name="C" />
        <Component2 name="D" />
      </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/react@17.0.4