@baublet/use-global-state
TypeScript icon, indicating that this package has built-in type declarations

1.1.0 • Public • Published

useGlobalState(key, initialValue = "")

CircleCI

A custom React hook for shared state. Typescript ready, isomorphic, and tiny. No additional, and fully tested.

Demonstration of shared state setup and tear down across n number of components

Installation

npm install --save @baublet/use-global-state

Use

This library is a custom hook, and thus follows all of the same requirements and conditions as React Hooks.

const MyComponent = () => {
  const [count, setCount] = useGlobalState("count", 0);
  return (
    <>
      <button onClick={() => setCount(count - 1)}>-</button>
      <div>{count}</div>
      <button onClick={() => setCount(count + 1)}>+</button>
    </>
  );
};

All hooks with the same key will share state and update together.

import * as React from "react";
import * as ReactDOM from "react-dom";
import { useGlobalState } from "use-global-state";

function App() {
  return (
    <div>
      <h1>Use Global State</h1>
      <ChildComponent />
      <ChildComponent />
      <ChildComponent />
    </div>
  );
}

// Each of these components will share state with one another
const ChildComponent = () => {
  const [count, setCount] = useGlobalState("count", 0);
  return (
    <>
      <hr />
      <button onClick={() => setCount(count - 1)} data-testid="dec">
        -
      </button>
      &nbsp;
      <div data-testid="count">{count}</div>
      &nbsp;
      <button onClick={() => setCount(count + 1)} data-testid="inc">
        +
      </button>
    </>
  );
};

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Package Sidebar

Install

npm i @baublet/use-global-state

Weekly Downloads

10

Version

1.1.0

License

ISC

Unpacked Size

52.4 kB

Total Files

12

Last publish

Collaborators

  • baublet