Global React hook useState

Matt Stypa
2 min readFeb 6, 2019

--

Kedge, easy to use global state hook for React

Kedge adds new useStore hook that feels and behaves a lot like useState except that it is shared globally.

Installation

npm install kedge

Usage

Previously, React state was an object that contained multiple properties describing the state of the component.

useState changed this. State is now a single value that represents a single property of the component. As such, components have multiple state objects.

The same principle applies to stores created with useStore. Store is a single value and an application will most likely have more than one.

When creating stores, I recommend doing so in a centralized location.

# store.jsimport { createStore } from 'kedge';export default {
firstName: createStore('John'),
lastName: createStore('Doh'),
};

We can now use these stores like this.

# profile.jsimport { useStore } from 'kedge';
import store from './store.js'
export default function Profile() {
const firstName = useStore(store.firstName);
const lastName = useStore(store.lastName);

return (
<>
<div>First name: {firstName}</div>
<div>Last name: {lastName}</div>
</>
);
}

Any changes made to these stores will cause all components that use them to be updated.

# randomizer.jsimport faker from 'faker';
import { useStore } from 'kedge';
import store from './store.js'
function setRandomNames() {
store.firstName.set(faker.name.firstName());
store.lastName.set(faker.name.lastName());
}
export default function Profile() {
return (
<button onclick={setRandomNames}>Randomize</button>
);
}

--

--

Matt Stypa

Calm work culture advocate. Open source contributor. Lead software engineer @ http://neighborhoods.com