Skip to content

Latest commit

Β 

History

History
48 lines (38 loc) Β· 965 Bytes

useMethods.md

File metadata and controls

48 lines (38 loc) Β· 965 Bytes

useMethods

React hook that simplifies the useReducer implementation.

Usage

import { useMethods } from 'react-use';

const initialState = {
  count: 0,
};

function createMethods(state) {
  return {
    reset() {
      return initialState;
    },
    increment() {
      return { ...state, count: state.count + 1 };
    },
    decrement() {
      return { ...state, count: state.count - 1 };
    },
  };
}

const Demo = () => {
  const [state, methods] = useMethods(createMethods, initialState);

  return (
    <>
      <p>Count: {state.count}</p>
      <button onClick={methods.decrement}>-</button>
      <button onClick={methods.increment}>+</button>
    </>
  );
};

Reference

const [state, methods] = useMethods(createMethods, initialState);
  • createMethods β€” function that takes current state and return an object containing methods that return updated state.
  • initialState β€” initial value of the state.