My blog

Sometimes I win the impostor syndrome

25/07/2024

Can you use a React hook for URL states?

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. ```typescript 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. <br/> **2) Improved State Management**: Simplifies state management and persists on reload.<br/> **3) SEO Benefits**: Makes dynamic content discoverable by search engines.<br/> **4) Consistent State Across Components**: Easily manage state across components.<br/> **5) Debugging and Testing**: Reproduce and share specific app states for easier debugging.<br/> **6) Flexibility and Scalability**: Efficiently scale state management.<br/> ## Usage Example Here's how you can use the `useQueryParams` hook in a component: ```typescript 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.

#frontend

#react