[]previous and next page

useReducer

A state cell whose writes go through a reducer: dispatch(action) stores reducer(state, action).

A state cell whose writes go through a reducer: dispatch(action) stores reducer(state, action). Equivalent to useSignal with the transition written in one place, which keeps every state change of a complex value (a form, a queue) in one function. Reads are fresh immediately after dispatch, like every write.

Import#

ts
import { useReducer } from "@shadow-js/core";

Signature#

ts
function useReducer<S, A>(
  reducer: (state: S, action: A) => S,
  initialState: S,
  options?: ReducerOptions,
): [Accessor<S>, (action: A) => void]

Parameters#

Name Description
reducer Pure function (state, action) => next.
initialState Starting state, stored as is.
options Equality override and a devtools name. Undefined uses the defaults.

Returns#

[state, dispatch]; state() tracks, dispatch(action) returns nothing. The reducer runs untracked, once per dispatch.

Throws#

  • ShadowError WRITE_IN_MEMO from dispatch, in development builds only, when it is called while a useMemo computation runs. dispatch also rethrows what the reducer throws.

Examples#

ts
import { useReducer } from "@shadow-js/core";

type Action = "inc" | "dec";
const [count, dispatch] = useReducer((n: number, a: Action) => (a === "inc" ? n + 1 : n - 1), 0);
dispatch("inc");
console.log(count()); // 1