Ecosyste.ms: Awesome

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

Awesome Lists | Featured Topics | Projects

https://github.com/benjamminf/react-twine

React state management library. As if we need another.
https://github.com/benjamminf/react-twine

react state-management

Last synced: 8 days ago
JSON representation

React state management library. As if we need another.

Awesome Lists containing this project

README

        

# react-twine

## Creating state

```jsx
const counterState = createState(0);

function Counter() {
const [count, setCounter] = useSharedState(counterState);
const increment = () => setCounter(count + 1);

return {count};
}
```

## Creating actions

```jsx
const counterState = createState(0);
const incrementAction = createAction(({value, set}) =>
set(counterState, count => count + value)
);

function Counter() {
const count = useValue(counterState);
const increment = useAction(incrementAction, 1);

return {count};
}
```

## Creating selectors

```jsx
const counterState = createState(0);
const counterDoubleSelector = createSelector(({get}) => get(counterState) * 2);

function Counter() {
const [count, setCounter] = useSharedState(counterState);
const countDouble = useValue(counterDoubleSelector);
const increment = () => setCounter(count + 1);

return (


{count} * 2 = {countDouble}


);
}
```

## Creating proxy state

```jsx
const counterState = createState(0);
const counterDoubleState = createProxyState(
({get}) => get(counterState) * 2,
({value, set}) => set(counterState, value / 2)
);

function Counter() {
const [count, setCounter] = useSharedState(counterState);
const [countDouble, setCounterDouble] = useSharedState(counterDoubleState);
const increment = () => setCounter(count + 1);
const incrementDouble = () => setCounterDouble(countDouble + 1);

return (


{count} * 2 =
{countDouble}


);
}
```

## Creating state factories

```jsx
const itemStates = createStateFactory(key => `Item ${key}`);

function Item(props) {
const item = useValue(itemStates(props.itemKey));

return

This item: {item}

;
}
```

## Initializing state asynchronously

```jsx
const counterState = createState(async () => {
await delay(1000);
return 0;
});

function Counter() {
const [count, setCounter] = useAsyncState(counterState);
const increment = () => setCounter(count => count + 1);

return {count ?? 'loading...'};
}
```

## Selecting asynchronously

```jsx
const counterState = createState(0);
const counterDoubleSelector = createSelector(async ({get}) => {
const counter = get(counterState);
await delay(1000);
return counter * 2;
});

function Counter() {
const [count, setCounter] = useSharedState(counterState);
const [countDouble] = useAsyncValue(counterDoubleSelector);
const increment = () => setCounter(count + 1);

return (


{count} * 2 =
{countDouble ?? 'loading...'}


);
}
```