MRT logoMantine React Table

On This Page

    State Management Guide

    Mantine React Table does not try to hide any of its internal state from you. You can initialize state with custom initial values, manage individual states yourself as you discover the need to have access to them, or store your own reference to the entire table instance wherever you need to.

    This is all optional, of course. If you do not need access to any of the state, you do not need to do anything and it will just automatically be managed internally.

    See the State Options API Docs for more information on which states are available for you to manage.

    Relevant Table Options

    #
    Prop Name
    Type
    Default Value
    More Info Links
    1Partial<MRT_TableState<TData>>Table State Management Guide
    2Partial<MRT_TableState<TData>>Table State Management Guide

    Populate Initial State

    If all you care about is setting parts of the initial or default state when the table mounts, then you may be able to specify that state in the initialState prop and not have to worry about managing the state yourself.

    For example, let's say you do not need access to the showColumnFilters state, but you want to set the default value to true when the table mounts. You can do that with the initialState prop:

    const table = useMantineReactTable({
      columns,
      data,
      initialState: {
        density: 'xs', //set default density to compact
        expanded: true, //expand all rows by default
        pagination: { pageIndex: 0, pageSize: 15 }, //set different default page size
        showColumnFilters: true, //show filters by default
        sorting: [{ id: 'name', desc: false }], //sort by name ascending by default
      },
    });
    
    return <MantineReactTable table={table} />;

    Note: If you use both initialState and state, the state initializer in state prop will take precedence and overwrite the same state values in initialState. So just use either initialState or state, not both for the same states.

    Manage Individual States as Needed

    It is pretty common to need to manage certain state yourself, so that you can react to changes in that state, or have easy access to it when sending it to an API.

    You can pass in any state that you are managing yourself to the state prop, and it will be used instead of the internal state. Each state property option also has a corresponding on[StateName]Change callback that you can use set/update your managed state as it changes internally in the table.

    For example, let's say you need to store the pagination, sorting, and row selection states in a place where you can easily access it in order to use it in parameters for an API call.

    const [pagination, setPagination] = useState({
      pageIndex: 0,
      pageSize: 15, //set different default page size by initializing the state here
    });
    const [rowSelection, setRowSelection] = useState({});
    const [sorting, setSorting] = useState([{ id: 'name', desc: false }]);
    
    //see example at bottom of page for alternatives to useEffect here
    useEffect(() => {
      //do something when the pagination state changes
    }, [pagination]);
    
    const table = useMantineReactTable({
      columns,
      data,
      getRowId: (originalRow) => row.username,
      onPaginationChange: setPagination,
      onRowSelectionChange: setRowSelection,
      onSortingChange: setSorting,
      state: { pagination, rowSelection, sorting }, //must pass states back down if using their on[StateName]Change callbacks
    });
    
    return <MantineReactTable table={table} />;

    Add Side Effects in Set State Callbacks

    In React 18 and beyond, it is becoming more discouraged to use useEffect to react to state changes, because in React Strict Mode (and maybe future versions of React), the useEffect hook may run twice per render. Instead, more event driven functions are recommended to be used. Here is an example for how that looks here. The callback signature for the on[StateName]Change works just like a React setState callback from the useState hook. This means that you have to check if the updater is a function or not, and then call the setState function with the updater callback if it is a function.

    const [pagination, setPagination] = useState({
      pageIndex: 0,
      pageSize: 15,
    });
    
    const handlePaginationChange = (updater: MRT_Updater<PaginationState>) => {
      //call the setState as normal, but need to check if using an updater callback with a previous state
      setPagination((prevPagination) =>
        //if updater is a function, call it with the previous state, otherwise just use the updater value
        updater instanceof Function ? updater(prevPagination) : updater,
      );
      //put more code for your side effects here, guaranteed to only run once, even in React Strict Mode
    };
    
    const table = useMantineReactTable({
      columns,
      data,
      onPaginationChange: handlePaginationChange,
      state: { pagination },
    });
    
    return <MantineReactTable table={table} />;

    Read From the Table Instance

    Note: Previously, in early MRT v1 betas, you could use the tableInstanceRef prop to get access to the table instance. This is no longer necessary as the useMantineReactTable hook now just returns the table instance directly.

    The useMantineReactTable hook returns the table instance. The <MantineReactTable /> needs the table instance for all of its internal logic, but you can also use it for your own purposes.

    const table = useMantineReactTable({
      columns,
      data,
      //...
    });
    
    const someEventHandler = (event) => {
      console.info(table.getRowModel().rows); //example - get access to all page rows in the table
      console.info(table.getSelectedRowModel()); //example - get access to all selected rows in the table
      console.info(table.getState().sorting); //example - get access to the current sorting state without having to manage it yourself
    };
    
    return (
      <div>
        <ExternalButton onClick={someEventHandler}>
          Export or Something
        </ExternalButton>
        <MantineReactTable table={table} />
      </div>
    );

    The table instance is the same object that you will also see as a provided parameter in many of the other callback functions throughout Mantine React Table, such as all the render... props or the Cell or Header render overrides in the column definition options.

    const columns = useMemo(
      () => [
        {
          Header: 'Name',
          accessor: 'name',
          Cell: ({ cell, table }) => <span>{cell.getValue()}</span>,
          //The `table` parameter from the Cell option params and the `table` are the same object
        },
      ],
      [],
    );
    
    const table = useMantineReactTable({
      columns,
      data,
      renderTopToolbarCustomActions: ({ table }) => {
        //The `table` parameter here and the table returned from the hook are the same object
        return <Button>Button</Button>;
      },
    });
    
    return <MantineReactTable table={table} />;

    Persistent State

    Persistent state is not a built-in feature of Mantine React Table, but it is an easy feature to implement yourself using the above patterns with the state prop and the on[StateName]Change callbacks. Here is an example of how you might implement persistent state using sessionStorage:

    First Name
    Last Name
    City
    State
    Salary
    AllisonBrownOmahaNebraska10000
    HarrySmithHickmanNebraska20000
    SallyWilliamsonAllianceNebraska30000
    LebronJamesIndianapolisIndiana40000
    MichaelMcGinnisHarrisonburgVirginia150000
    JosephWilliamsValentineNebraska100000
    NoahBrownToledoOhio50000
    MasonZhangSacramentoCalifornia100000
    VioletDoeSan FranciscoCalifornia100000

    Rows per page

    1-9 of 9

    import '@mantine/core/styles.css';
    import '@mantine/dates/styles.css'; //if using mantine date picker features
    import 'mantine-react-table/styles.css'; //make sure MRT styles were imported in your app root (once)
    import { useEffect, useRef, useState } from 'react';
    import { Button } from '@mantine/core';
    import {
      MantineReactTable,
      useMantineReactTable,
      type MRT_ColumnDef,
      type MRT_ColumnFiltersState,
      type MRT_DensityState,
      type MRT_SortingState,
      type MRT_VisibilityState,
    } from 'mantine-react-table';
    import { data, type Person } from './makeData';
    
    const columns: MRT_ColumnDef<Person>[] = [
      {
        accessorKey: 'firstName',
        header: 'First Name',
      },
      {
        accessorKey: 'lastName',
        header: 'Last Name',
      },
      {
        accessorKey: 'city',
        header: 'City',
      },
      {
        accessorKey: 'state',
        header: 'State',
      },
      {
        accessorKey: 'salary',
        header: 'Salary',
      },
    ];
    
    const Example = () => {
      const isFirstRender = useRef(true);
    
      const [columnFilters, setColumnFilters] = useState<MRT_ColumnFiltersState>(
        [],
      );
      const [columnVisibility, setColumnVisibility] = useState<MRT_VisibilityState>(
        {},
      );
      const [density, setDensity] = useState<MRT_DensityState>('md');
      const [globalFilter, setGlobalFilter] = useState<string | undefined>(
        undefined,
      );
      const [showGlobalFilter, setShowGlobalFilter] = useState(false);
      const [showColumnFilters, setShowColumnFilters] = useState(false);
      const [sorting, setSorting] = useState<MRT_SortingState>([]);
    
      //load state from local storage
      useEffect(() => {
        const columnFilters = sessionStorage.getItem('mrt_columnFilters_table_1');
        const columnVisibility = sessionStorage.getItem(
          'mrt_columnVisibility_table_1',
        );
        const density = sessionStorage.getItem('mrt_density_table_1');
        const globalFilter = sessionStorage.getItem('mrt_globalFilter_table_1');
        const showGlobalFilter = sessionStorage.getItem(
          'mrt_showGlobalFilter_table_1',
        );
        const showColumnFilters = sessionStorage.getItem(
          'mrt_showColumnFilters_table_1',
        );
        const sorting = sessionStorage.getItem('mrt_sorting_table_1');
    
        if (columnFilters) {
          setColumnFilters(JSON.parse(columnFilters));
        }
        if (columnVisibility) {
          setColumnVisibility(JSON.parse(columnVisibility));
        }
        if (density) {
          setDensity(JSON.parse(density));
        }
        if (globalFilter) {
          setGlobalFilter(JSON.parse(globalFilter) || undefined);
        }
        if (showGlobalFilter) {
          setShowGlobalFilter(JSON.parse(showGlobalFilter));
        }
        if (showColumnFilters) {
          setShowColumnFilters(JSON.parse(showColumnFilters));
        }
        if (sorting) {
          setSorting(JSON.parse(sorting));
        }
        isFirstRender.current = false;
      }, []);
    
      //save states to local storage
      useEffect(() => {
        if (isFirstRender.current) return;
        sessionStorage.setItem(
          'mrt_columnFilters_table_1',
          JSON.stringify(columnFilters),
        );
      }, [columnFilters]);
    
      useEffect(() => {
        if (isFirstRender.current) return;
        sessionStorage.setItem(
          'mrt_columnVisibility_table_1',
          JSON.stringify(columnVisibility),
        );
      }, [columnVisibility]);
    
      useEffect(() => {
        if (isFirstRender.current) return;
        sessionStorage.setItem('mrt_density_table_1', JSON.stringify(density));
      }, [density]);
    
      useEffect(() => {
        if (isFirstRender.current) return;
        sessionStorage.setItem(
          'mrt_globalFilter_table_1',
          JSON.stringify(globalFilter ?? ''),
        );
      }, [globalFilter]);
    
      useEffect(() => {
        if (isFirstRender.current) return;
        sessionStorage.setItem(
          'mrt_showGlobalFilter_table_1',
          JSON.stringify(showGlobalFilter),
        );
      }, [showGlobalFilter]);
    
      useEffect(() => {
        if (isFirstRender.current) return;
        sessionStorage.setItem(
          'mrt_showColumnFilters_table_1',
          JSON.stringify(showColumnFilters),
        );
      }, [showColumnFilters]);
    
      useEffect(() => {
        if (isFirstRender.current) return;
        sessionStorage.setItem('mrt_sorting_table_1', JSON.stringify(sorting));
      }, [sorting]);
    
      const resetState = () => {
        sessionStorage.removeItem('mrt_columnFilters_table_1');
        sessionStorage.removeItem('mrt_columnVisibility_table_1');
        sessionStorage.removeItem('mrt_density_table_1');
        sessionStorage.removeItem('mrt_globalFilter_table_1');
        sessionStorage.removeItem('mrt_showGlobalFilter_table_1');
        sessionStorage.removeItem('mrt_showColumnFilters_table_1');
        sessionStorage.removeItem('mrt_sorting_table_1');
        window.location.reload();
      };
    
      const table = useMantineReactTable({
        columns,
        data,
        onColumnFiltersChange: setColumnFilters,
        onColumnVisibilityChange: setColumnVisibility,
        onDensityChange: setDensity,
        onGlobalFilterChange: setGlobalFilter,
        onShowColumnFiltersChange: setShowColumnFilters,
        onShowGlobalFilterChange: setShowGlobalFilter,
        onSortingChange: setSorting,
        state: {
          columnFilters,
          columnVisibility,
          density,
          globalFilter,
          showColumnFilters,
          showGlobalFilter,
          sorting,
        },
        renderTopToolbarCustomActions: () => (
          <Button onClick={resetState}>Reset State</Button>
        ),
      });
    
      return <MantineReactTable table={table} />;
    };
    
    export default Example;