How to remove query parameters with React Router hooks?

Sometimes, we want to remove query parameters with React Router hooks.

In this article, we’ll look at how to remove query parameters with React Router hooks.

How to remove query parameters with React Router hooks?

To remove query parameters with React Router hooks, we can use the history.replace method with the an object argument with the search property set to the new query string.

For instance, we write

import React, { useState, useEffect } from "react";
import { useHistory, useLocation } from "react-router-dom";

export default function Foo() {
  const location = useLocation();
  const history = useHistory();

  useEffect(() => {
    const queryParams = new URLSearchParams(location.search);

    if (queryParams.has("error")) {
      queryParams.delete("error");
      history.replace({
        search: queryParams.toString(),
      });
    }
  }, []);

  return <>Component</>;
}

to get the query string from location.search.

Then we parse it with URLSearchParams into an object.

And then we check if the query string has the error parameter with queryParams.has.

If it’s true, we call queryParams.delete to remove the query string.

And then we call history.replace with an object with the new query string that we get with queryParans.toString to replace the query string with the new one.

Conclusion

To remove query parameters with React Router hooks, we can use the history.replace method with the an object argument with the search property set to the new query string.