reactjsurlsearchparams

How to prevent re-rendering when changing search param?


There is a small component in which, when you click on the button, the search param changes in the url. But when search param changes, the entire component is re-rendered, is it possible to make it so that only the url changes, without a re-render? Or maybe 'use-query-params' is not so good idea to use here?

import React from 'react';
    import { StringParam, useQueryParam } from 'use-query-params';
    import cl from './Footer.module.scss';
    
    const Footer = () => {
          const [tab, setTab] = useQueryParam('ptab', StringParam);
        
          const handleClick = e => setTab(e.target.name);
        
          const getClass = name => {
            const values = ['tab1', 'tab2', 'tab3'];
        
            if (tab === name || (name === 'tab4' && (!tab || !values.includes(tab)))) return cl.active;
            return '';
          };
        
          return (
            <ul className={cl.footer}>
              <li>
                <button name='tab1' onClick={handleClick} className={getClass('tab1')}>
                  Tab1
                </button>
              </li>
              <li>
                <button name='tab2' onClick={handleClick} className={getClass('tab2')}>
                  Tab2
                </button>
              </li>
              <li>
                <button name='tab3' onClick={handleClick} className={getClass('tab3')}>
                  Tab3
                </button>
              </li>
            </ul>
          );
        };
        
        export default Footer;

Solution

  • You can use the JS history API. Here a short example that should help you:

    import "./styles.css";
    
    export default function App() {
      const handleClick = (e) => {
        const url = new URL(window.location);
        url.searchParams.set("tab", e.target.name);
        window.history.pushState({}, "", url);
      };
    
      return (
        <ul>
          <li>
            <button name="tab1" onClick={handleClick}>
              Tab1
            </button>
          </li>
          <li>
            <button name="tab2" onClick={handleClick}>
              Tab2
            </button>
          </li>
          <li>
            <button name="tab3" onClick={handleClick}>
              Tab3
            </button>
          </li>
        </ul>
      );
    }
    

    Here the Link to the codesandbox: https://codesandbox.io/s/hardcore-babycat-rz1v9?file=/src/App.js:0-584