Blog>
Snippets

Integrating Search Param Serialization with State Management

Demonstrate integrating custom search param serialization and deserialization with a state management library (e.g., Redux or Vuex), keeping the application state and URL in sync using TanStack Router.
import { useSelector, useDispatch } from 'react-redux';
import { useSearchParams } from 'tanstack-react-query';
import { useEffect } from 'react';

// Action to set state from URL
const setStateFromURL = (params) => ({
  type: 'SET_STATE_FROM_URL',
  payload: params,
});

// Serializes state object to search params
function serializeStateToSearchParams(state) {
  const searchParams = new URLSearchParams();
  Object.entries(state).forEach(([key, value]) => {
    searchParams.set(key, JSON.stringify(value));
  });
  return searchParams;
}

// Deserializes search params to state object
function deserializeSearchParamsToState(searchParams) {
  const state = {};
  searchParams.forEach((value, key) => {
    state[key] = JSON.parse(value);
  });
  return state;
}

// Custom hook to sync state with URL
export function useSyncStateWithURL() {
  const state = useSelector((state) => state);
  const dispatch = useDispatch();
  const [searchParams, setSearchParams] = useSearchParams();

  useEffect(() => {
    // On mount, deserialize URL to state
    const initState = deserializeSearchParamsToState(searchParams);
    dispatch(setStateFromURL(initState));
  }, []);

  useEffect(() => {
    // On state change, serialize state to URL
    const newSearchParams = serializeStateToSearchParams(state);
    setSearchParams(newSearchParams);
  }, [state]);
}
This snippet demonstrates how to integrate custom search param serialization and deserialization with Redux state management, keeping the application state and URL synchronized using TanStack Router. It defines actions for setting state from URL, serializes and deserializes state to/from search params, and custom hooks to sync state with the URL on state change or component mount.