React

The URL is a great place to store state in React

Mar 11, 2025
8 min read
The URL is a great place to store state in React

# The URL is a great place to store state in React

Sometimes, the best place to store state is right in the URL. It's simple, practical, and often overlooked. Let's explore why it's worth considering.

## The Problem

Here's what we want to achieve: Let's say we have a modal (dialog) component that allows the user to perform some important actions which are part of the core flow. We would like the modal to stay open even after the user reloads the page.

If we were to just use `useState` for the modal `open` state, we would lose this information when the page reloads. Let's see how we can solve this problem.

## Ways to Store State on the Client

Let's look at the options we have to store state to achieve the desired behavior. The options can generally be categorized as follows:

### In the Application
Data that belongs in the working memory of the application. Lasts as long as the application is running.

```javascript
const App = () => {
const [open, setOpen] = useState(false);
return setOpen(false)} />;
};
```

### In the Browser
Data that is stored in the browser. Examples include `localStorage` and `sessionStorage`.

```javascript
const App = () => {
const [open, setOpen] = useState(() => {
try {
return localStorage.getItem("modalOpen") === "true";
} catch (error) {
console.error("Failed to read from localStorage:", error);
return false; // Default fallback value
}
});

useEffect(() => {
try {
localStorage.setItem("modalOpen", open);
} catch (error) {
console.error("Failed to write to localStorage:", error);
}
}, [open]);

return setOpen(false)} />;
};
```

### In the URL
This is the encoded data stored in the URL in the form of a `string`. Good examples are Query Parameters (`"/users?userId=desc"`) and Path Parameters (`"/users/1324"`).

## Why choose the URL

As with everything, there are pros and cons to each approach.

### Pros
  • Shareable between users: The URL is accessible to anyone who has the link to the page
    - Fast: Reading from the URL is generally faster than reading from localStorage
    - Global: The state is global and can be accessed by any component
    - Navigation-friendly: The state can leave a trail in the browser history

    ### Cons
    - Hard to debug and maintain: When state is stored in the URL, it can be challenging to trace issues
    - Hard to scale: Storing large amounts of state in the URL can lead to lengthy URLs
    - Not type-safe out of the box: URL parameters are typically strings, requiring additional parsing

    ## How to store state in the URL

    Using `useSearchParams` (React Router):

    ```javascript
    import { useSearchParams } from "react-router-dom";

    function Example() {
    const [searchParams, setSearchParams] = useSearchParams();
    const updateParam = () => {
    setSearchParams({ filter: "active" });
    };

    return (


    Current Filter: {searchParams.get("filter")}



    );
    }
    ```

    ## Conclusion

    Choosing where to store state depends on its purpose and how it interacts with the application. Query parameters are ideal when state should persist across page reloads, be shareable via URL, and affect navigation.
  • Enjoyed this article?

    Follow me on social media for more insights on web development and technology.