Spooky Ghost Haunted Docs Toggle darkmode

Hooks: useReducer

Similarly to useState, useReducer will return an array of two values, the first one being the state. The second one, however, is dispatch. This is a function that takes an action. The action is then passed to your reducer (the first argument) and your reducer will determine the new state and return it.

The following is an example of useReducer being used to handle incrementing and decrementing a count:

import { component, html, useReducer } from 'haunted';

// doesn't have to be an object, could just be `initialState = 0`
const initialState = { count: 0 };

function reducer(state, action) {
  switch (action.type) {
    case 'reset':
      return initialState;
    case 'increment':
      return { count: state.count + 1 };
    case 'decrement':
      return { count: state.count - 1 };

function Counter() {
  const [state, dispatch] = useReducer(reducer, initialState);

  return html`
    Count: ${state.count}
    <button @click=${() => dispatch({ type: 'reset' })}>
    <button @click=${() => dispatch({ type: 'increment' })}>+</button>
    <button @click=${() => dispatch({ type: 'decrement' })}>-</button>

customElements.define('use-reducer', component(Counter));

This might look familiar as redux uses a similar concept.



Given a reducer function, initial state, and optional state initializer function, returns a tuple of state and dispatch function.



Reducer<S, A>

reducer function to compute the next state given the previous state and the action



the initial state of the reducer


(init: I) => S

Optional initializer function, called on initialState if provided


readonly [S, (action: A) => void]


import { useReducer } from 'haunted/lib/use-reducer';