Skip to content
A simpler way to useReducers
Branch: master
Clone or download
Latest commit 43382d4 Apr 15, 2019
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
src Minor typing tweaks Apr 16, 2019
test Add support for lazy initialization (resolves #10) Apr 16, 2019
tools
vscode Add source and test code Mar 26, 2019
.editorconfig Initial commit Mar 26, 2019
.gitignore Initial commit Mar 26, 2019
.prettierignore
.prettierrc.yml Add source and test code Mar 26, 2019
.travis.yml Use latest node version only in CI Mar 26, 2019
CONTRIBUTING.md Initial commit Mar 26, 2019
LICENSE Update date on LICENSE Mar 27, 2019
README.md Tweak wording Apr 16, 2019
code-of-conduct.md Initial commit Mar 26, 2019
package.json v0.4.7 Apr 16, 2019
tsconfig.json Remove rollup Mar 26, 2019
tslint.json Initial commit Mar 26, 2019
yarn.lock Use immer directly instead of use-immer, fix #7 Mar 29, 2019

README.md

use-methods Build Status

Installation

Pick your poison:

  • npm install use-methods
    
  • yarn add use-methods
    

Usage

This library exports a single React Hook, useMethods, which has all the power of useReducer but none of the ceremony that comes with actions and dispatchers. The basic API follows a similar pattern to useReducer:

const [state, callbacks] = useMethods(methods, initialState);

Instead of providing a single "reducer" function which is one giant switch statement over an action type, you provide a set of "methods" which modify the state or return new states. Likewise, what you get back in addition to the latest state is not a single dispatch function but a set of callbacks corresponding to your methods.

A full example:

import useMethods from 'use-methods';

function Counter() {

  const [
    { count }, // <- latest state
    { reset, increment, decrement }, // <- callbacks for modifying state
  ] = useMethods(methods, initialState);

  return (
    <>
      Count: {count}
      <button onClick={reset}>Reset</button>
      <button onClick={increment}>+</button>
      <button onClick={decrement}>-</button>
    </>
  );
}

const initialState = { count: 0 };

const methods = state => ({
  reset() {
    return initialState;
  },
  increment() {
    state.count++;
  },
  decrement() {
    state.count--;
  },
});

Comparison to useReducer

Here's a more complex example involving a list of counters, implemented using useReducer and useMethods respectively:

useReducer vs useMethods comparison

Which of these would you rather write?

Immutability

use-methods is built on immer, which allows you to write your methods in an imperative, mutating style, even though the actual state managed behind the scenes is immutable. You can also return entirely new states from your methods where it's more convenient to do so (as in the reset example above).

Memoization

Like the dispatch method returned from useReducer, the callbacks returned from useMethods aren't recreated on each render, so they will not be the cause of needless re-rendering if passed as bare props to React.memoized subcomponents. Save your useCallbacks for functions that don't map exactly to an existing callback! In fact, the entire callbacks object (as in [state, callbacks]) is memoized, so you can use this to your deps array as well:

const [state, callbacks] = useMethods(methods, initialState);

// can pass to event handlers props, useEffect, etc:
const MyStableCallback = useCallback((x: number) => {  
  callbacks.someMethod('foo', x);
}, [callbacks]);

// which is equivalent to:
const MyOtherStableCallback = useCallback((x: number) => {
  callbacks.someMethod('foo', x);
}, [callbacks.someMethod]);

Types

This library is built in TypeScript, and for TypeScript users it offers an additional benefit: one no longer needs to declare action types. The example above, if we were to write it in TypeScript with useReducer, would require the declaration of an Action type:

type Action =
  | { type: 'reset' }
  | { type: 'increment' }
  | { type: 'decrement' };

With useMethods the "actions" are implicitly derived from your methods, so you don't need to maintain this extra type artifact.

If you need to obtain the type of the resulting state + callbacks object that will come back from useMethods, use the StateAndCallbacksFor operator, e.g.:

const MyContext = React.createContext<StateAndCallbacksFor<typeof methods> | null>(null);
You can’t perform that action at this time.