Search code examples
react-routerbrowser-history

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


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?


Solution

  • 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);
    };