DEV Community

Max Wiggedal
Max Wiggedal

Posted on

React state in query

When working with state in React it can quickly turn into several useState being used and something you might not think about is that the user might want to share the page with their friends while persisting the state, implementing that can be quite tricky and require more work than necessary. An easy solution to this is by utilizing query parameters for the state.

Normal State

For example you might have this stateful datatable component:

export default function DataTable() {
    const [page, setPage] = useState(1);
    const [size, setSize] = useState(10);
    const [search, setSearch] = useState("");

    return (
        <div>
            <p>Page: {page}</p>
            <p>Size: {size}</p>
            <p>Search: {search}</p>
        </div>
    );
}
Enter fullscreen mode Exit fullscreen mode

This works just fine, however if the user wants to share the page with a friend and have it display the exact same values (assuming they have been modified from default state) then that would not be possible.

Query Parameters State

Instead we could implement state using query parameters:

export default function DataTable() {
    const [searchParams, setSearchParams] = useSearchParams();
    const page = parseInt(searchParams.get("page")) || 1;
    const size = parseInt(searchParams.get("size")) || 10;
    const search = searchParams.get("search") || "";

    // Example: updateState("page", 3);
    const updateState = (key, value) => {
        setSearchParams((previousSearchParams) => {
            previousSearchParams.set(key, value);
            return previousSearchParams;
        }, { replace: true });
    }

    return (
        <div>
            <p>Page: {page}</p>
            <p>Size: {size}</p>
            <p>Search: {search}</p>
        </div>
    );
}
Enter fullscreen mode Exit fullscreen mode

This way we would be able to share the link to the page to a friend and they would see the exact same results as we do, for example: https://example.com/?page=2&size=1

Top comments (0)