state-as-reducer
TypeScript icon, indicating that this package has built-in type declarations

1.0.7 • Public • Published

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();

Package Sidebar

Install

npm i state-as-reducer

Weekly Downloads

0

Version

1.0.7

License

MIT

Unpacked Size

14.2 kB

Total Files

8

Last publish

Collaborators

  • juliuskoronci