Product
Introducing SSO
Streamline your login process and enhance security by enabling Single Sign-On (SSO) on the Socket platform, now available for all customers on the Enterprise plan, supporting 20+ identity providers.
use-methods
Advanced tools
Readme
use-methods
Pick your poison:
npm install use-methods
yarn add use-methods
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.
useReducer
Here's a more complex example involving a list of counters, implemented using useReducer
and useMethods
respectively:
Which of these would you rather write?
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);
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.memo
ized subcomponents. Save your useCallback
s 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]);
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);
FAQs
A simpler way to useReducers
The npm package use-methods receives a total of 1,842 weekly downloads. As such, use-methods popularity was classified as popular.
We found that use-methods demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Product
Streamline your login process and enhance security by enabling Single Sign-On (SSO) on the Socket platform, now available for all customers on the Enterprise plan, supporting 20+ identity providers.
Security News
Tea.xyz, a crypto project aimed at rewarding open source contributions, is once again facing backlash due to an influx of spam packages flooding public package registries.
Security News
As cyber threats become more autonomous, AI-powered defenses are crucial for businesses to stay ahead of attackers who can exploit software vulnerabilities at scale.