All Projects → rudyhuynh → use-url-search-params

rudyhuynh / use-url-search-params

Licence: MIT License
A React Hook to use URL query string as a state management

Programming Languages

typescript
32286 projects
javascript
184084 projects - #8 most used programming language
HTML
75241 projects
CSS
56736 projects
shell
77523 projects

Projects that are alternatives of or similar to use-url-search-params

react-europe-2019
Slides and demo app from my keynote
Stars: ✭ 29 (-43.14%)
Mutual labels:  react-hooks
Facebook-Messenger
This is a Facebook Messenger clone.You can comminicate to other at realtime.Used ReactJS, Material UI, Firebase, Firestore Database
Stars: ✭ 18 (-64.71%)
Mutual labels:  react-hooks
frontegg-react
Frontegg-React is pre-built Component for faster and simpler integration with Frontegg services.
Stars: ✭ 15 (-70.59%)
Mutual labels:  react-hooks
react-hooks-file-upload
React Hooks File Upload example with Progress Bar using Axios, Bootstrap
Stars: ✭ 30 (-41.18%)
Mutual labels:  react-hooks
window-scroll-position
React hook for Window scroll position
Stars: ✭ 81 (+58.82%)
Mutual labels:  react-hooks
MetFlix
A Movie app demo. Like NetFlix ❤️
Stars: ✭ 50 (-1.96%)
Mutual labels:  react-hooks
react
🎣 React hooks & components on top of ocean.js
Stars: ✭ 27 (-47.06%)
Mutual labels:  react-hooks
rxdb-hooks
React hooks for integrating with RxDB
Stars: ✭ 57 (+11.76%)
Mutual labels:  react-hooks
react-change-highlight
✨ a react component to highlight changes constantly ⚡️
Stars: ✭ 79 (+54.9%)
Mutual labels:  react-hooks
react-admin-nest
React和Ant Design和 Nest.js 和 Mysql 构建的后台通用管理系统。持续更新。
Stars: ✭ 123 (+141.18%)
Mutual labels:  react-hooks
react-hooks-example
React Hooks Example
Stars: ✭ 21 (-58.82%)
Mutual labels:  react-hooks
Fakeflix
Not the usual clone that you can find on the web.
Stars: ✭ 4,429 (+8584.31%)
Mutual labels:  react-hooks
react-social-network
react social network
Stars: ✭ 13 (-74.51%)
Mutual labels:  react-hooks
react-sendbird-messenger
ReactJS (React-router-dom v6 + Antdesign + Firebase + Sendbird + Sentry) codebase containing real world examples (CRUD, auth, advanced patterns, etc).
Stars: ✭ 39 (-23.53%)
Mutual labels:  react-hooks
how-react-hooks-work
Understand how React-hook really behaves, once and for all!
Stars: ✭ 73 (+43.14%)
Mutual labels:  react-hooks
MERN-BUS-APP
This is a MFRP (My first Real Project) assigned to me during my internship at Cognizant. Made with MERN Stack technology.
Stars: ✭ 92 (+80.39%)
Mutual labels:  react-hooks
react-emotion-multi-step-form
React multi-step form library with Emotion styling
Stars: ✭ 25 (-50.98%)
Mutual labels:  react-hooks
react-store
A library for better state management in react hooks world
Stars: ✭ 34 (-33.33%)
Mutual labels:  react-hooks
react-hook-form-auto
Automatic form generation using ReactHookForm
Stars: ✭ 45 (-11.76%)
Mutual labels:  react-hooks
atomic-state
A decentralized state management library for React
Stars: ✭ 54 (+5.88%)
Mutual labels:  react-hooks

useUrlSearchParams()

GitHub license

A React Hook to use URL query string as a state management

Demo

Why you need this

  • Your app need to persist its state after user refresh the page (used for simple, non-sensitive data).
  • Some page settings (ex: table filter, sorting, paging, etc.) should be saved in the URL so that user can easily pass to others. e.g. Tester can easily send a URL of a page to developer with very least reproduce steps.
  • You want to do something (request new data, etc.) every time some URL query value changes.
  • Combine all of the above with a URL query as a single source of truth.

Installation

npm install use-url-search-params

or

yarn add use-url-search-params

How to use

For most of the time you will do something like this:

import React from "react";
import { useUrlSearchParams } from "use-url-search-params";

function App() {
  // Your page URL will be like this by default: http://my.page?checked=true
  const [params, setParams] = useUrlSearchParams({ checked: true });

  React.useEffect(() => {
    // do something when `params.checked` is updated.
  }, [params.checked]);

  return (
    <div>
      <input type="checkbox" checked={params.checked} onChange={(e) => setParams({ checked: e.target.checked })} />
    </div>
  );
}

How to control the value parsed from URL query

By default, all values parsed from URL query are string. In case you want to get boolean or number value, pass a second argument to useUrlSearchParams() to specify data type you want to get from params object. Here is an example:

const initial = {
  y: "option1",
};
const types = {
  x: Number,
  y: Boolean,
  z: Date,
  t: ["option1", "option2", "option3"],
};
const [params, setParams] = useUrlSearchParams(initial, types);

// `params.x` will be number (or NaN)
// `params.y` will be one of [undefined, true, false]
// `params.z` will be instance of Date (can be Invalid Date)
// `params.t` will be one of ["option1", "option2", "option3"] (can be `undefined` if not specified in `initial`)

Complex data structure

Although you can use JSON.parse() and JSON.stringify() to get/set arbitrary serializable data to URL query, it is not recommended. URL query is a good place to store and persist page settings as key/value pairs such as table filter, sorting, paging, etc. We should keep it that way for simplicity. For complex data structure, you should consider using other state management for better performance, security and flexibility.

WARNING: Be aware of XSS attack. Be careful to validate values from URL query before using it by either using types - the second parameter passed to useUrlSearchParams() or validate them yourself if neccessary.

But if you still insist, here is an example:

function App() {
  const [params, setParams] = useUrlSearchParams(
    {},
    {
      complexData: (dataString) => {
        try {
          return JSON.parse(dataString);
        } catch (e) {
          return {};
        }
      },
    }
  );

  const onSetParams = (data) => {
    setParams({ complexData: JSON.stringify(data) });
  };

  return <div>{/*...*/}</div>;
}

React Router

Should just work with React Router or any routing system. Just make sure that your component re-render whenever route changes.

API

  • useUrlSearchParams([initial, types, replace])
    • initial (optional | Object): To set default values for URL query string.
    • types (optional | Object): Has similar shape with initial, help to resolve values from URL query string. Supported types:
      • String (default)
      • Number
      • Bool
      • Date - Date​.prototype​.toISOString() is used to parse date to string, e.g date string in your URL query is zero UTC offset
      • Array of available string values (like enum)
      • A custom resolver function
    • replace (optional | boolean | default: false): If true, will call histor#replaceState() instead of history#pushState() on url search param change.

Read more (for maintainers)

This library is built base on URLSearchParams interface

License

MIT

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].