useReducerActions

useReducer with actions

npm npm bundle size

Install

npm install @react-things/use-reducer-actions
yarn add @react-things/use-reducer-actions

Usage

import { useReducerActions } from '@react-things/use-reducer-actions';

const Counter = () => {
  const [
    count,
    { increment, decrement, incrementByAmount },
  ] = useReducerActions({
    initialState: 0,
    reducers: {
      increment: state => state + 1,
      decrement: state => state - 1,
      incrementByAmount: (state, amount: number) => state + amount,
    },
  });

  return (
    <div>
      <div>
        <button onClick={decrement}>-</button>
        <div data-testid="count">{count}</div>
        <button onClick={increment}>+</button>
      </div>
      <div>
        <button onClick={() => incrementByAmount(3)}>Increment by 3</button>
      </div>
    </div>
  );
};

import { useReducerActions } from '@react-things/use-reducer-actions';

type Todo = {
  id: string;
  text: string;
  isDone: boolean;
};

const Todos = () => {
  const [todos, { addTodo }] = useReducerActions({
    initialState: [] as Todo[],
    reducers: {
      addTodo: (state, todo: Todo) => [...state, todo],
    },
  });

  return (
    <div>
      <ul>
        {todos.map(todo => {
          return (
            <li key={todo.id}>
              {todo.text}
              {todo.isDone && '✅'}
            </li>
          );
        })}
      </ul>
      <button
        onClick={() => {
          addTodo({ id: '1', text: 'New todo', isDone: false });
        }}
      >
        Add todo
      </button>
    </div>
  );
};

GitHub

View Github