re-state
API Reference

useReStateSelector

Use useReStateSelector when a component needs derived data from one or more state keys. The selector runs after store updates, but the component re-renders only when the selected result changes.

import { useReStateSelector } from '@raulpesilva/re-state';

type AppState = {
  todos: Array<{ id: string; finished: boolean }>;
  filter: 'all' | 'finished';
};

export function VisibleTodoCount() {
  const count = useReStateSelector<AppState, number>((state) => {
    if (state.filter === 'finished') {
      return state.todos.filter((todo) => todo.finished).length;
    }

    return state.todos.length;
  });

  return <output>Visible todos: {count}</output>;
}

AppState describes the keyed state object passed to the selector. It is only a TypeScript type; you do not create or pass a store instance to the hook.

The keys used by a selector must be initialized before the component renders. Keys that do not exist are absent from the runtime object.

Equality checks

The default comparison is shallow equality. Primitives use Object.is semantics, while objects and arrays are compared one level deep.

Pass a second argument when the selected value needs different rules:

const selectedIds = useReStateSelector<AppState, string[]>(
  (state) => state.todos.map((todo) => todo.id),
  (previous, next) => previous.length === next.length && previous.every((id, index) => id === next[index])
);

The equality function should return true when React can keep the previous selected result.

Subscription scope

This hook listens to the complete store because a selector may read several keys. The selector can therefore run after an unrelated key changes, even when the component does not re-render.

For one key without derived data, use createReStateSelect or the generated use<Name>Select hook from createReStateMethods.

API

function useReStateSelector<Store, Selection = unknown>(
  selector: (store: Store) => Selection,
  isEquals?: (storeA: Selection, storeB: Selection) => boolean
): Selection;
ParameterDescription
selectorReturns the value exposed to the component
isEqualsOptional comparison function; defaults to shallow equality
Type parameterDescription
StoreTypeScript shape of the complete keyed state
SelectionValue returned by selector

On this page