Can you use a React hook for URL states?

frontend,

react

2 min read

25/07/2024

Managing URL parameters in a React application can be simplified with React Router’s useSearchParams hook. Here’s a custom hook, useQueryParams, for easy handling of URL query parameters.

Custom Hook: useQueryParams

The useQueryParams hook uses useSearchParams to get, set, compare, and delete query parameters.

import { useSearchParams } from 'react-router-dom'

const useQueryParams = () => {
  const [params, setSearchParams] = useSearchParams()

  const getQueryParam = (key) => params.get(key)
  const setQueryParam = (key, value) =>
    setSearchParams((prev) => {
      prev.set(key, value)
      return prev
    })
  const isQueryParamEqual = (key, value) => params.get(key) === value
  const getBooleanQueryParam = (key) => params.get(key) === 'true'
  const setBooleanQueryParam = (key, value) =>
    setSearchParams((prev) => {
      prev.set(key, value ? 'true' : 'false')
      return prev
    })
  const deleteQueryParam = (key) =>
    setSearchParams((prev) => {
      prev.delete(key)
      return prev
    })

  return {
    getQueryParam,
    setQueryParam,
    isQueryParamEqual,
    getBooleanQueryParam,
    setBooleanQueryParam,
    deleteQueryParam,
  }
}

export default useQueryParams

Advantages of Managing URL States

1) Enhanced User Experience: Bookmark and share exact app states.
2) Improved State Management: Simplifies state management and persists on reload.
3) SEO Benefits: Makes dynamic content discoverable by search engines.
4) Consistent State Across Components: Easily manage state across components.
5) Debugging and Testing: Reproduce and share specific app states for easier debugging.
6) Flexibility and Scalability: Efficiently scale state management.

Usage Example

Here’s how you can use the useQueryParams hook in a component:

const MyComponent = () => {
  const { getQueryParam, setQueryParam, deleteQueryParam } = useQueryParams()

  useEffect(() => {
    const value = getQueryParam('myParam')
    console.log('Current value:', value)
  }, [getQueryParam])

  const handleSetParam = () => {
    setQueryParam('myParam', 'newValue')
  }

  const handleDeleteParam = () => {
    deleteQueryParam('myParam')
  }

  return (
    <div>
      <button onClick={handleSetParam}>Set Param</button>
      <button onClick={handleDeleteParam}>Delete Param</button>
    </div>
  )
}

export default MyComponent

In this example, MyComponent uses the useQueryParams hook to get, set, and delete a query parameter called myParam. This makes URL state management straightforward and integrates seamlessly with your React application.

myself

Hey there, I'm Guilherme. I'm a software developer and learning passionate based in Brazil.

You can see some of my work on GitHub or read more about me on my website.