Blog>
Snippets

Persisting State Across Sessions

Explain how to integrate TanStack Store with a persistence mechanism to save and load state from local storage, ensuring state persistence across sessions.
import { useLocalStorageState } from '@tanstack/react-table';

function usePersistedState(key, defaultValue) {
  const [state, setState] = useLocalStorageState(key, {
    defaultValue,
  });

  return [state, setState];
}
This snippet defines a custom hook, usePersistedState, leveraging TanStack's useLocalStorageState hook to save and load state from local storage. It abstracts away the logic for persisting state across sessions, taking a unique key and a default value as parameters.
const [tableState, setTableState] = usePersistedState('tableState', initialState);

// When setting the table state
setTableState(newTableState);
Here, the usePersistedState hook is utilized for the table's state management, allowing the state to persist across sessions. 'tableState' is the key under which state is saved in local storage. This approach enables the table state to be saved and restored automatically, ensuring a consistent experience for the user.