Blog>
Snippets

Saving User Preferences for Column Visibility

Use local storage to save and restore user preferences for column visibility in React TanStack Table, ensuring a personalized UI experience.
const [visibleColumns, setVisibleColumns] = React.useState(()=> {
  // Attempt to load saved user preferences from localStorage
  const savedPrefs = localStorage.getItem('userColumnVisibilityPrefs');
  return savedPrefs ? JSON.parse(savedPrefs) : ['defaultColumnIds'];
});
Initializes the state for visible columns, attempting to restore preferences from localStorage if available. If no preferences are saved, fallback to default.
React.useEffect(() => {
  // Save the current state of visibleColumns to localStorage whenever it changes
  localStorage.setItem('userColumnVisibilityPrefs', JSON.stringify(visibleColumns));
}, [visibleColumns]);
Uses useEffect to monitor changes to visibleColumns state. When changes occur, the new state is serialized and saved to localStorage, ensuring user preferences are preserved across sessions.
const tableInstance = useReactTable({
  // Other table options...
  initialState: { columnVisibility: visibleColumns },
  onColumnVisibilityChange: newVisible => {
    setVisibleColumns(newVisible);
  }
  // Additional table configuration...
});
Configures the ReactTable instance. Sets an initial state for column visibility based on the state. Also, defines a handler for onColumnVisibilityChange to update the state, thereby saving the new preferences.