Blog>
Snippets

Persisting Column Order State

Show how to save and restore column order state between user sessions using local storage, ensuring a personalized experience across sessions.
const saveColumnOrder = (columns) => {
  localStorage.setItem('columnOrder', JSON.stringify(columns.map(c => c.id)));
};
Saves the current column order to the local storage. It serializes the array of column IDs.
const restoreColumnOrder = (defaultColumns) => {
  const storedOrder = JSON.parse(localStorage.getItem('columnOrder'));
  if (!storedOrder) return defaultColumns;
  return storedOrder.map(columnId => defaultColumns.find(c => c.id === columnId)).filter(Boolean);
};
Restores the column order from local storage. It matches stored IDs with the default columns array to reconstruct the previous order, filtering out any missing columns.
const columns = [...]; // Your initial columns setup
const restoredColumns = restoreColumnOrder(columns);
// Use the restoredColumns for your data grid's column definition
Demonstrates how to use the restoreColumnOrder function to get the column array based on the user's previous session and then use it to set up the data grid.