Manage page state in React apps by using the History API to store the state.

Rate this post

Preface

There are many state management libraries in React, such as Redux, Rematch, Recoil, and of course, you can use React context to manage page state. These are all very useful, but there is a problem — when we refresh the page, the page state will be lost, and the page state will not be shareable. For example, if you filter some data in a React app list page, and expect to share the page URL with somebody who can directly see the result, you can’t implement it only with the state management.

This article will introduce the use of the History API to enhance the React state so that the state can be shared and the page display will not change after refreshing the page.

Persistent State with URL

Most of the npm modules use localStorage to persist the page state in React applications like redux-persist — npm (npmjs.com)use-persisted-state — npm (npmjs.com). By using localStorage, we can store complex data or large data, and when refreshing the page, we can restore the state, it is a better experience for users, especially on a mobile page.

For most of the list pages, we only need to persist some state of filtering action, we can use a URL to store the state. Supposing that we only need to store one field, we can use this React hook:

const useHistory = () => {
  const { pathname, search } = window.location;
  const queryParams = new URLSearchParams(search);
  const [filter, setFilter] = React.useState(queryParams.get("filter") || "");
  return [
    text,
    function setData(val) {
      setFilter(val);
      queryParams.set("filter", val);
      history.replaceState({}, "", `${pathname}?${queryParams.toString()}`);
    }
  ];
};

Once using the hook function, it will get the URL query filter to initial the filter variable, and we can use setData to store the state and it will store the state to URL.

There is a React app demo:

See the Pen using history as state manage by bitbug (@bitbug) on CodePen.

By using URL to persist the state, and we can share the link (CodePen doesn’t share for it uses iframe for rendering the result page).

Conclusion

We can use localStorage to persist state, but also can use URL to do it. If we need to share a page URL with some preset filter/option, using the URL to store the state will be convenient. If the state data is very large, we can save it to backend SQL with a short id that can be shared with others.

We use URLSearchParams to parse URL query and set field, you can learn more about parsing query by referring to this article:

Leave a Comment

4 + two =

CRICKET LIVE STREAMING