Skip to content

useDefaultReducer

Manage object-shaped state with shallow partial updates. Built on React's useReducer with a typed patchState helper.

Import

import { useDefaultReducer } from 'medhira-react-typescript-hooks';
import type { UseDefaultReducerReturn } from 'medhira-react-typescript-hooks';

Signature

function useDefaultReducer<S extends Record<string, unknown>>(
  initialState: S,
): UseDefaultReducerReturn<S>;

Parameters

Parameter Type Required Description
initialState S Yes Initial state object (defines the state shape)

Returns

Property Type Description
state S Current state
patchState (patch: Partial<S>) => void Shallow-merge patch into state
multipleAction (patch: Partial<S>) => void Deprecated — alias of patchState

Behavior

stateDiagram-v2
    [*] --> Idle: mount with initialState
    Idle --> Updated: patchState(partial)
    Updated --> Updated: patchState(partial)
  • Updates are shallow: nested objects are replaced, not deep-merged.
  • Unknown keys in patch are allowed by TypeScript only when they exist on S.
  • Each call to patchState schedules one reducer update.

Example (TypeScript)

type FormState = {
  email: string;
  password: string;
};

function LoginForm() {
  const { state, patchState } = useDefaultReducer<FormState>({
    email: '',
    password: '',
  });

  return (
    <input
      value={state.email}
      onChange={(e) => patchState({ email: e.target.value })}
    />
  );
}

Example (JavaScript)

const { state, patchState } = useDefaultReducer({
  email: '',
  password: '',
});

patchState({ email: 'user@example.com' });

When to use something else

Scenario Alternative
Deep nested updates useImmer, dedicated reducer, or normalized state
Primitive state useState
Complex action types Custom useReducer in your app
Server/async state React Query, SWR, etc.

Migration from multipleAction

multipleAction still works but is deprecated. Prefer patchState:

- multipleAction({ email: value })
+ patchState({ email: value })