1.0.7 • Published 2 years ago

state-as-reducer v1.0.7

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

useStateReducer

A simple implementation of useState with useReducer.

Why?

  • useState doesnt work well with nested objects or complex states
  • you should not pass down the set state fn to children or if you pass id down you need to wrap it in a useCallback
  • useReducer has too much boilerplate for simple use cases

How to use

Basic

const [state, setState] = useStateReducer();

setState - in this case wraps around dispatch and can be safely passed around. You will not encounter references to unmounted components. state by default will be undefined.

With objects as intial state:

const [state, setState] = useStateReducer({data: 'test'});

Async state producers

const fetchMyData = async () => Promise.resolve(['test'])

const [state, setState, { loading, failed, error }] = useStateReducer([], fetchMyData);

The above illustrates how we can fill in the state with data returned from a promise which often time is needed on component mount. The same api is supported for setState:

const fetchMyData = async () => Promise.resolve(['test'])

const [state, setState, { loading, failed, error }] = useStateReducer([]);

setState(fetchMyData);

This will resolve the promise and update the state accordingly while still supporting the original useState api, e.g.

Counter

const [state, setState] = useStateReducer(0);

setState(currentCount => currentCount + 1);

Reset

const [state, setState, { reset }] = useStateReducer([]);

reset();
1.0.7

2 years ago

1.0.6

2 years ago

1.0.5

2 years ago

1.0.4

3 years ago

1.0.3

3 years ago

1.0.2

3 years ago

1.0.1

3 years ago

1.0.0

3 years ago