codegino
← all posts

Sync React application state with the URL

A simplified approach to managing external states

8 min read#react#tech

sink
sink

TL;DR


Introduction

Wouldn't it be great if we can allow our application to store its state, and we can easily share it with others? For instance, on the GIF below, we can sort a table by the different properties; then, the URL will update accordingly. And the next time the same URL is loaded, the user will see the same view.


An image of a blog post

Of course, it could be more complex; instead of a table, use a card view filtered by the multiple properties and sorted by age in descending order, etc.

This idea is pretty common, but the question is, how do we implement it?


What do we need to implement the feature?

Below are typical high-level steps to develop the requirement

  1. Create an App component to store and load data
  2. Create the Table component
  3. Have a place to store the sort state
  4. Handle updating the URL when a table header is clicked
  5. Fetch the URL state, then update the component

Steps 1 & 2 are probably the easiest, as they are our average react components.

Step 1: Create the plain version of the App that store and load data

App.jsx
1const App = () => {2  const [data, setData] = React.useState([]);3
4  useEffect(() => {5    fetch('https://jsonplaceholder.typicode.com/users')6      .then(response => response.json())7      .then(json => setData(json));8  }, []);9
10  return (11    <div>12      <Table data={data} />13    </div>14  );15};16
17export default App;

Step 2: Create a simple table component

components/Table.jsx
1const Table = ({data}) => {2  return (3    <table>4      <thead>5        <tr>6          <th>Username</th>7          <th>Name</th>8          <th>website</th>9        </tr>10      </thead>11      <tbody>12        {data.map(item => {13          return (14            <tr key={item.username}>15              <td>{item.username}</td>16              <td>{item.name}</td>17              <td>{item.website}</td>18            </tr>19          );20        })}21      </tbody>22    </table>23  );24};25
26export default Table;

Complicated solution

Before going to the straightforward solution, let's see another way a React developer might do it.


Step 3: Store the sortBy state using the React.useState hook

Instead of putting sortBy in the Table component, we lift the state from the table to the parent component to present data differently(i.e. Card View)

App.jsx
1const App = () => {2  const [sortBy, setSortBy] = React.useState('');3
4	// Create a sortedData based on the value of `sortProp`5  const sortedData = sortBy6    ? [...data].sort((a, b) => {7        const firstValue = a[sortBy];8        const secondValue = b[sortBy];9
10        return firstValue && secondValue11          ? firstValue.localeCompare(secondValue)12          : 0;13      })14    : data;15
16  return (17    <div>18      <Table data={sortedData} sortBy={sortBy} setSortBy={setSortBy} />19    </div>20  );21}

Step 4.1: Add table headers event handler

Add an event listener when a table header is clicked; then, propagate the event to the parent component.

components/Table.jsx
1const Table = ({data, setSortBy, sortBy}) => {2  const handleSorting = (value) => {3    setSortBy(value === sortBy ? '' : value);4  };5
6  return (7    <table>8      <thead>9        <tr>10          <th onClick={() => handleSorting('username')}>Username</th>11          <th onClick={() => handleSorting('name')}>Name</th>12          <th onClick={() => handleSorting('website')}>website</th>13        </tr>14      </thead>15      {/* ... */}16    </table>17	)18}

Step 4.2: Saving the React-related state to the URL

Saving the state to the URL is just as simple as changing the URL itself. The way to change the URL depends on your routing library of choice. For the example below, I used the classic react-router.

components/Table.jsx
1import { useNavigate, createSearchParams } from 'react-router-dom';2
3const Table = ({data, setSortBy, sortBy}) => {4  // react-outer utility hook to manage navigation5  const navigate = useNavigate();6
7  const handleSorting = (value) => {8    // Check if the new value is the active sortBy value9    const isActiveSort = value === sortBy;10
11    // Update sortBy in the React land12    setSortBy(isActiveSort ? '' : value);13
14    // Update sortBy in the URL land15    if (isActiveSort) {16      navigate({});17    } else {18      navigate({19        search: `?${createSearchParams({20          sortBy: value,21        })}`,22      });23    }24  };25
26  // return ...27}

Step 5: Loading State from URL

Before rendering our component, we retrieve the state of the URL and update the value of our sortBy state.

App.jsx
1import {useSearchParams} from 'react-router-dom';2
3const App = () => {4  const [sortBy, setSortBy] = React.useState('');5
6  // React router utility hook to get the query params7  const [searchParams] = useSearchParams();8
9  useEffect(() => {10    const sortByQuery = searchParams.get('sortBy');11
12    setSortBy(sortByQuery);13  }, [searchParams]);14
15  // return ...16}

Now, it should be working as expected!

An image of a blog post

But what if we have more queries to process?

If we follow the previous approach, our code might look like this.

App.jsx
1const App = () => {2  const [sortBy, setSortBy] = React.useState('');3  const [sortByOrder, setSortByOrder] = React.useState('');4  const [filterBy, setFilterBy] = React.useState('');5  const [view, setView] = React.useState('table');6  const [focusedRow, setFocusedRow] = React.useState(-1)7
8  const [searchParams] = useSearchParams();9
10  useEffect(() => {11    const sortByQuery = searchParams.get('sortBy');12    const filterByQuery = searchParams.get('filterBy');13    const viewQuery = searchParams.get('view');14    const focusedRowQuery = searchParams.get('focusedRow');15
16    setSortBy(/* Derive sort field from sortByQuery */);17    setSortByOrder(/* Derive sort order from sortByQuery */);18    setFilterBy(filterByQuery);19    setView(viewQuery);20    setFocusedRow(focusedRowQuery);21  }, [searchParams]);22
23
24  const sortedData = // process sorted data25
26  return (27    <div>28      <Table data={sortedData}29        sortBy={sortBy} setSortBy={setSortBy}30        sortByOrder={sortByOrder} setSortByOrder={setSortByOrder}31        filterBy={filterBy} setFilterBy={setFilterBy}32        view={view} setView={setView}33        focusedRow={focusedRow} setFocusedRow={setFocusedRow}34      />35    </div>36  );37}

You might say that we can just use a useReducer or some state management, but it does not address the root of the issue.


What is the issue were are trying to solve?

The problem is creating two sources of truth: our React state and the URL state. The worse part is if we update those states separately. If possible, follow the DRY principle.


Simplified solution

Step 3: Use the actual URL object as the single source of truth

There is no need to create an additional state that we can track and modify. Simply derive the queries from the URL, and store the value in something immutable.

App.jsx
1const App = () => {2  // const [sortBy, setSortBy] = React.useState('');3  // const [searchParams] = useSearchParams();4
5  // useEffect(() => {6  //   const sortByQuery = searchParams.get('sortBy');7  //   setSortBy(sortByQuery);8  // }, [searchParams]);9
10
11  // This is the simplified version of Step 512  const [searchParams] = useSearchParams();13  const sortBy = searchParams.get('sortBy') || '';14
15  // ...16}

Step 4(Simplified): Update the URL directly

Our table component does not need to propagate state changes to the parent component. By updating the URL directly, we can effectively revise our single source of truth.

components/Table.jsx
1// const Table = ({data, setSortBy, sortBy}) => {2const Table = ({data}) => {3  const [searchParams] = useSearchParams();4  const sortBy = searchParams.get('sortBy');5
6  const handleSorting = (value) => {7    // Check if the new value is the active sortBy value8    const isActiveSort = value === sortBy;9
10    // setSortBy(isActiveSort ? '' : value);11
12    if (isActiveSort) {13      navigate({});14    } else {15      navigate({16        search: `?${createSearchParams({17          sortBy: value,18        })}`,19      });20    }21  };22
23  return (24    <table>25      <thead>26        <tr>27          <th onClick={() => handleSorting('username')}>Username</th>28          <th onClick={() => handleSorting('name')}>Name</th>29          <th onClick={() => handleSorting('website')}>website</th>30        </tr>31      </thead>32      {/* ... */}33    </table>34	)35}

Since we just need to update the URL to update the state, we can even leverage the default behavior of HTML to update our state.

components/Table.jsx
1import {Link, useSearchParams} from 'react-router-dom';2
3const Table = ({data}) => {4  const [searchParams] = useSearchParams();5  const sortBy = searchParams.get('sortBy');6
7  // To avoid repetition in the `to` attribute8  const createToLink = (sortValue) => {9    return sortBy === sortValue ? '/' : `?sortBy=${sortValue}`;10  };11
12  return (13    <table>14      <thead>15        <tr>16          <th>17            <Link to={createToLink('username')}>Username</Link>18          </th>19          <th>20            <Link to={createToLink('name')}>Name</Link>21          </th>22          <th>23            <Link to={createToLink('website')}>Website</Link>24          </th>25        </tr>26      </thead>27      {/* ... */}28    </table>29  )30}

Final Solution

App.jsx
1import React, {useEffect} from 'react';2import {useSearchParams} from 'react-router-dom';3import Table from './Table';4
5const App = () => {6  const [data, setData] = React.useState([]);7
8  useEffect(() => {9    fetch('https://jsonplaceholder.typicode.com/users')10      .then(response => response.json())11      .then(json => setData(json));12  }, []);13
14
15  // Implementing full sorting behavior is not the focus of this blog16  // That is why the following code magically appears here17  const [searchParams] = useSearchParams();18  const sortBy = searchParams.get('sortBy') || '';19  const [sortProp, order] = sortBy ? sortBy.split(':') : [];20
21
22  const sortedData = sortBy23    ? [...data].sort((a, b) => {24        const firstValue = a[sortProp];25        const secondValue = b[sortProp];26
27        if (!firstValue || !secondValue) {28          return 0;29        }30
31        return order === 'desc'32          ? secondValue.localeCompare(firstValue)33          : firstValue.localeCompare(secondValue);34      })35    : data;36
37  return (38    <div>39      <Table data={sortedData} />40    </div>41  );42};43
44export default App;

More about the single source of truth thingy

If we want to create a custom table header component, we don't need to deal with prop drilling because our single source of truth is in the URL itself.

It's like we use the URL as Redux.

components/SortableTableHeader.jsx
1const SortableTableHeader = ({sortValue, children, ...props}) => {2  const [searchParams] = useSearchParams();3
4  const sortBy = searchParams.get('sortBy');5
6  const [sortProp, order] = sortBy ? sortBy.split(':') : [];7
8  const createToLink = () => {9    if (sortValue === sortProp) {10      if (!order) {11        return `?sortBy=${sortValue}:desc`;12      } else {13        return '/';14      }15    } else {16      return `?sortBy=${sortValue}`;17    }18  };19
20  const sortSymbol = () => {21    if (sortValue === sortProp) {22      return !order ? '️⬇️' : '⬆️';23    }24    return '';25  };26
27  return (28    <th {...props}>29      <Link to={createToLink()}>{children}{sortSymbol()}</Link>30    </th>31  );32};

It just looks amazing how we could eliminate prop drilling.

components/Table.jsx
1import React from 'react';2import {Link, useSearchParams} from 'react-router-dom';3
4const Table = ({data}) => {5  return (6    <table>7      <thead>8        <tr>9          <SortableTableHeader sortValue="username">Username</SortableTableHeader>10          <SortableTableHeader sortValue="name">Name</SortableTableHeader>11          <SortableTableHeader sortValue="website">Website</SortableTableHeader>12        </tr>13      </thead>14      <tbody>15        {data.map(item => {16          return (17            <tr key={item.username}>18              <td>{item.username}</td>19              <td>{item.name}</td>20              <td>{item.website}</td>21            </tr>22          );23        })}24      </tbody>25    </table>26  );27};28
29export default Table;

After applying the additional changes, we're back to our desired behavior

An image of a blog post

This pattern can also be used for other states, such as app storage and server state(react-query); also with other frameworks.

Conclusion

It's easy to miss a more straightforward solution because of the pattern that we are used to. The point here is not about avoiding the usage useState, useReducer, redux, etc. It is more on utilizing the web's default behavior to reduce our code's complexity.