Synchronize React State with URL Parameters
Use useSyncExternalStore to synchronize React state with query parameters in the URL, making the component respond to URL changes.
import { useSyncExternalStore } from 'react';
import { useLocation, useHistory } from 'react-router-dom';
// Custom hook to synchronize React state with URL query parameters
function useQueryParams(key, defaultValue) {
const location = useLocation();
const history = useHistory();
// Parse query parameters
const queryParams = new URLSearchParams(location.search);
const state = queryParams.get(key) || defaultValue;
// Update URL when state changes
const setState = (newState) => {
queryParams.set(key, newState);
history.push(`${location.pathname}?${queryParams}`);
};
// Subscribe to perist changes
const subscribe = (callback) => {
return history.listen(() => {
if (queryParams.get(key) !== state) {
callback();
}
});
};
// Synchronize React state with the URL parameter
const value = useSyncExternalStore(
subscribe,
() => queryParams.get(key) || defaultValue
);
return [value, setState];
}
This custom hook uses useSyncExternalStore to synchronize React state with a specific query parameter from the URL. By using useLocation and useHistory from react-router-dom, it listens to changes in the URL and updates the component's state accordingly. Additionally, it provides a setState function to update the URL when the state changes.