If you are working with React and using react-router for routing, you might come across a situation where you need to programmatically update the query parameters in the URL. This can be useful when you want to update the URL based on user actions or when you want to pass data between different components.

Solution 1: Using useHistory hook

One way to programmatically update query params in react-router is by using the useHistory hook provided by react-router-dom. This hook gives you access to the history object, which allows you to manipulate the browser history.
Here’s an example of how you can use the useHistory hook to update query params:


      import React from 'react';
      import { useHistory } from 'react-router-dom';
      
      function MyComponent() {
        const history = useHistory();
        
        const updateQueryParams = () => {
          // Get the current location object
          const location = history.location;
          
          // Get the current query params
          const queryParams = new URLSearchParams(location.search);
          
          // Update the query params
          queryParams.set('param1', 'value1');
          queryParams.set('param2', 'value2');
          
          // Create a new search string with updated query params
          const newSearch = queryParams.toString();
          
          // Update the URL with the new search string
          history.push({
            ...location,
            search: newSearch
          });
        };
        
        return (
          
); }

In this example, we first import the useHistory hook from react-router-dom. Then, we use it to get the history object. Inside the updateQueryParams function, we get the current location object and extract the query params using the URLSearchParams API. We then update the query params using the set method and create a new search string with the updated query params using the toString method. Finally, we update the URL by calling the push method on the history object and passing the updated location object.

Solution 2: Using the useLocation and useNavigate hooks

Another way to programmatically update query params in react-router is by using the useLocation and useNavigate hooks provided by the react-router-dom package. The useLocation hook gives you access to the current location object, while the useNavigate hook allows you to navigate to a different location.
Here’s an example of how you can use these hooks to update query params:


      import React from 'react';
      import { useLocation, useNavigate } from 'react-router-dom';
      
      function MyComponent() {
        const location = useLocation();
        const navigate = useNavigate();
        
        const updateQueryParams = () => {
          // Get the current query params
          const queryParams = new URLSearchParams(location.search);
          
          // Update the query params
          queryParams.set('param1', 'value1');
          queryParams.set('param2', 'value2');
          
          // Create a new search string with updated query params
          const newSearch = queryParams.toString();
          
          // Update the URL with the new search string
          navigate({
            ...location,
            search: newSearch
          });
        };
        
        return (
          
); }

In this example, we use the useLocation hook to get the current location object and the useNavigate hook to get the navigate function. Inside the updateQueryParams function, we follow a similar process as in the previous solution to update the query params and create a new search string. Finally, we update the URL by calling the navigate function and passing the updated location object.

Conclusion

Updating query params programmatically in react-router can be achieved using either the useHistory hook or the combination of the useLocation and useNavigate hooks. Both solutions allow you to manipulate the query params in the URL based on user actions or other dynamic factors. Choose the solution that best fits your project requirements and coding style.