npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

use-methods

v0.5.1

Published

A simpler way to useReducers

Downloads

16,936

Readme

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--;
  },
});

Note: the methods factory function must produce the same set of method names on every invocation.

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).

If you would like to use the patches functionality from immer, you can pass an object to useMethods that contains the methods property and a patchCallback property. The callback will be fed the patches applied to the state. For example:

const patchList: Patch[] = [];
const inverseList: Patch[] = [];

const methodsObject = {
  methods: (state: State) => ({
    increment() {
      state.count++;
    },
    decrement() {
      state.count--;
    }
  }),
  patchCallback: (patches: Patch[], inversePatches: Patch[]) => {
    patchList.push(...patches);
    inverseList.push(...inversePatches);
  },
};

// ... and in the component
const [state, { increment, decrement }] = useMethods(methodsObject, initialState);

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