npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

use-hash-state

v2.0.1

Published

Store application state in the URL hash

Downloads

19

Readme

use-hash-state

Hook to read and write React state from the URL hash

// https://my-app#{hello:"world"}

const {
  state: { hello },
} = useHashState({});
// hello === "world"

Why?

For simple demos and proofs of concepts, it often suffices to store state in the client, without a database.

URLs are a good place to store data:

  • URLs are "serverless"
  • URLs can be bookmarked
  • URLs are easily shareable
  • Browser back and forward buttons allow accessing state over time

This hook is not a router, it merely synchronizes the state within a component with state stored in the URL.

I would not use this for any production system, but it's invaluable for sharing ideas with colleagues.

Installation

npm install --save use-hash-state

Usage

const { state, setStateAtKey } = useHashState(initialState, options);

Parameters

initialState

(type: {})

The state to start with, also used to determine what is considered a valid URL state by default (see the validateKeysAndTypes option below for more).

options

See Options argument below

Return values

state

The current state, preferentially taken from the URL.

setStateAtKey

(type: (key: keyof T, value: any) => void)

Updates the state at a particular key, also updating the URL.


In a simple counter component:

import React from 'react';
import useHashState from 'use-hash-state';

const Counter = () => {
  const initialState = {
    count: 0,
  };

  const { state, setStateAtKey } = useHashState(initialState);

  const handleIncrement = () => {
    setStateAtKey('count', state.count + 1);
  };

  return (
    <>
      <span>Count: {state.count}</span>
      <button onClick={handleIncrement}>Increment</button>
    </>
  );
};

Upon load, the URL hash will be set to the URL-encoded JSON representation of the initial state:

http://localhost:1234/#%7B%22count%22%3A2%7D

As Increment is clicked, setStateAtKey updates the state within the component, and the URL will be updated to reflect the internal state.

Reloading or sharing the link will cause the initialState to be ignored, in favor of the URL state.

Options argument

Options may be passed as the second argument to useHashState:

import useHashState, { UseHashStateOptions } from 'use-hash-state';

const MyComponent = () => {
  const initalState = {};

  const options: UseHashStateOptions = {
    usePushState: true, // boolean | undefined
    validateKeysAndTypes: true, // boolean | undefined
    customValidator: (obj: {}) => {
      return true;
    }, // (obj: {}) => boolean | undefined
  };

  const { state, setStateAtKey } = useHashState(initialState, options);

  // ...
};

usePushState

(type: boolean | undefined, default: false)

By default, useHashState uses history.replaceState to update the URL. This means that the back and forward buttons will ignore the URL updates made by this hook, which is suitable for quickly-updating state when you do not want a massively long history.

If you set usePushState to true, the hook will use history.pushState, so every state update will add a new history entry, and you will be able to use the browser next / previous buttons to access previous states.

validateKeysAndTypes

(type: boolean | undefined, default: true)

When validateKeysAndTypes is set to true (the default), the hook will check that any object in the URL has the same keys as the initialState that you provide, and that the values at those keys are also the same types as in initialState. If the URL state is not the same shape, it will be ignored, and the initial state will be applied.

This is handy for ensuring that your component state does not get super crazy because of some malformed URLs, particularly when you are developing and changing the shape of your state often.

customValidator

(type: (obj: {}) => boolean | undefined, default: undefined)

If you have a more complicated state that you'd like to validate, provide a customValidator, which will be passed the JSON object parsed from the URL. Return true if that object should be read into the local state, false otherwise.

This is useful for when you want to ensure that values have certain bounds.

Note that this is applied in addition to basic key and type validation if validateKeysAndTypes is set to true.

License

MIT