marmelab/react-admin · error · Error

useListSortContext must be used inside a ListSortContextProv

Error message

useListSortContext must be used inside a ListSortContextProvider

What it means

useListSortContext reads ListSortContext, which only exists under a ListSortContextProvider created by list controllers. Without it, the hook throws rather than returning undefined sort state.

Source

Thrown at packages/ra-core/src/controller/list/useListSortContext.ts:18

import { useContext } from 'react';

import { ListSortContext, ListSortContextValue } from './ListSortContext';

/**
 * Hook to read the list sort controller props from the ListSortContext.
 *
 * Must be used within a <ListSortContextProvider> (e.g. as a descendent of <List>
 * or <ListBase>).
 *
 * @returns {ListSortContextValue} list controller props
 *
 * @see useListController for how it is filled
 */
export const useListSortContext = (): ListSortContextValue => {
    const context = useContext(ListSortContext);
    if (!context) {
        throw new Error(
            'useListSortContext must be used inside a ListSortContextProvider'
        );
    }
    return context;
};

View on GitHub (pinned to 051f511bb0)

Solutions

  1. Nest the component inside a <List> page
  2. Wrap with ListSortContextProvider in tests/stories providing sort/setSort
  3. Use local useState for sort when no list is present

Example fix

// before
export const SortIndicator = () => {
  const { sort } = useListSortContext(); // throws
};
// after
<List>
  <SortIndicator />
</List>
Defensive patterns

Strategy: try-catch

Validate before calling

const ctx = useContext(ListSortContext);
if (!ctx) return <PlainHeader label="Title" />;

Type guard

const hasSortContext = (): boolean => useContext(ListSortContext) !== null;

Try / catch

try { render(<SortableHeader field="title" />); } catch (e) { if (String(e).includes('useListSortContext')) { /* nest inside List */ } }

Prevention

When it happens

Trigger: Calling useListSortContext in a component not nested under <List> or a manual <ListSortContextProvider value={{ sort, setSort }}>.

Common situations: Custom sort buttons/column headers rendered outside a list; unit tests missing the provider; reusing sort UI in non-list views.

Related errors


AI-assisted analysis of marmelab/react-admin@051f511bb0 (2026-08-30). Data as JSON: /api/errors/74375e15af3e4bc2. Report an issue: GitHub.