@baublet/use-global-state
v1.1.0
Published
[![CircleCI](https://circleci.com/gh/baublet/use-global-state.svg?style=svg)](https://circleci.com/gh/baublet/use-global-state)
Downloads
902
Maintainers
Readme
useGlobalState(key, initialValue = "")
A custom React hook for shared state. Typescript ready, isomorphic, and tiny. No additional, and fully tested.
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>
<div data-testid="count">{count}</div>
<button onClick={() => setCount(count + 1)} data-testid="inc">
+
</button>
</>
);
};
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);