reactjsreact-routerreact-hooks

How to remove query param with react hooks?


I know we can replace query params in component based classes doing something along the lines of:

  componentDidMount() {       
    const { location, replace } = this.props;   

    const queryParams = new URLSearchParams(location.search);   
    if (queryParams.has('error')) { 
      this.setError(    
        'There was a problem.'  
      );    
      queryParams.delete('error');  
      replace({ 
        search: queryParams.toString(), 
      });   
    }   
  }

Is there a way to do it with react hooks in a functional component?


Solution

  • For React Router V6 and above, see the answer below.


    Original Answer:

    Yes, you can use useHistory & useLocation hooks from react-router:

    
    import React, { useState, useEffect } from 'react'
    import { useHistory, useLocation } from 'react-router-dom'
    
    export default function Foo() {
      const [error, setError] = useState('')
    
      const location = useLocation()
      const history = useHistory()
    
      useEffect(() => {
        const queryParams = new URLSearchParams(location.search)
        
        if (queryParams.has('error')) {
          setError('There was a problem.')
          queryParams.delete('error')
          history.replace({
            search: queryParams.toString(),
          })
        }
      }, [])
    
      return (
        <>Component</>
      )
    }
    

    As useHistory() returns history object which has replace function which can be used to replace the current entry on the history stack.

    And useLocation() returns location object which has search property containing the URL query string e.g. ?error=occurred&foo=bar" which can be converted into object using URLSearchParams API (which is not supported in IE).