How to update the URL and replace history state in React Router v5 without re-rendering the whole app?

Viewed 445

There are a few situations triggering a re-render when using React Router and its browser history, that I would like to do without re-rendering the whole app:

  • using history.replace('currentPath', { data: 'someState' };

  • adding a param such as "?active=1" to the URL.

Is there a way to do it or the solution is to optimize some components for performance?

1 Answers

You can use history.replaceState() like this:

const setQueryParams = (param, value) => {
    const history = window.history;
    let currentUrlParams = new URLSearchParams(window.location.search);
    currentUrlParams.set(param, value);

    const url = `${window.location.pathname}?${currentUrlParams.toString()}`;
    history.replaceState({}, '', url);
};
Related