Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/minchingtonak/pocketstore

A pocket-sized, TypeScript-first global state store for react/preact.
https://github.com/minchingtonak/pocketstore

hooks pocket preact react store tiny

Last synced: about 1 month ago
JSON representation

A pocket-sized, TypeScript-first global state store for react/preact.

Awesome Lists containing this project

README

        

# pocketstore

A pocket-sized, TypeScript-first global state store for react/preact.

## Usage

### createStore

```ts
import createStore from 'pocketstore';

const initialValue = 'hello world';

// basic
const { getStore, setStore, useStore } = createStore(initalValue);

// with specific type
const { getStore, setStore, useStore } = createStore(
initalValue
);

// with reducer
type StoreAction =
| {
type: 'add';
value: string;
}
| {
type: 'clear';
};

const reducer = (store: string, action: StoreAction) => {
switch (action.type) {
case 'add':
return store + action.value;
case 'clear':
return '';
}
};

// creating a store with a reducer causes a dispatch() function to be returned
// instead of setStore().
const { getStore, dispatch, useStore } = createStore(initialValue, reducer);
```

### useStore hook

```tsx
import createStore from 'pocketstore';

const { setStore: setUserData, useStore: useUserData } = createStore({
name: '',
count: 0,
});

const NameEntryForm = () => {
// useStore allows mapping stored data to avoid unnecessary rerenders
// and provide a cleaner way of accessing the stored data
const name = useUserData(s => s.name);

const updateName = (e: ChangeEvent) => {
setUserData(d => ({ ...d, name: e.target.value }));
};

return ;
};

const UserInfo = () => {
const data = useUserData();

const onCountButtonClick = () =>
setUserData(d => ({ ...d, count: d.count + 1 }));

return (


User: {data.name}



Has clicked this button {data.count} times


);
};
```

## Credits

Based heavily on [react-hstore](https://github.com/stevekanger/react-hstore)