Skip to content

Files

Latest commit

author
Juan Lulkin
Feb 15, 2021
245e116 Β· Feb 15, 2021

History

History
61 lines (46 loc) Β· 1.18 KB

createGlobalState.md

File metadata and controls

61 lines (46 loc) Β· 1.18 KB

useGlobalState

A React hook that creates a globally shared state.

Usage

const useGlobalValue = createGlobalState<number>(0);

const CompA: FC = () => {
  const [value, setValue] = useGlobalValue();

  return <button onClick={() => setValue(value + 1)}>+</button>;
};

const CompB: FC = () => {
  const [value, setValue] = useGlobalValue();

  return <button onClick={() => setValue(value - 1)}>-</button>;
};

const Demo: FC = () => {
  const [value] = useGlobalValue();
  return (
    <div>
      <p>{value}</p>
      <CompA />
      <CompB />
    </div>
  );
};

It also allows initializing the state with a function and using a function in the setState:

const useGlobalValue = createGlobalState<number>(() => 0);

const CompA: FC = () => {
  const [value, setValue] = useGlobalValue();

  return <button onClick={() => setValue(value => value + 1)}>+</button>;
};

const CompB: FC = () => {
  const [value, setValue] = useGlobalValue();

  return <button onClick={() => setValue(value => value - 1)}>-</button>;
};

const Demo: FC = () => {
  const [value] = useGlobalValue();
  return (
    <div>
      <p>{value}</p>
      <CompA />
      <CompB />
    </div>
  );
};