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-state-proxy

v1.1.3

Published

Using Proxy API to auto dispatch React.useState

Downloads

309

Readme

use-state-proxy

Using Proxy API to auto dispatch React.useState(). Inspired from @State() in @stencil/core.

npm Package Version

Installation

## using npm
npm install use-state-proxy

## or using yarn
yarn add use-state-proxy

## or using pnpm
pnpm install use-state-proxy

Typescript Signature

type StateProxy<T extends object> = T

// auto trigger re-render when in-place update occurs
export function useStateProxy<T extends object>(initialValue: T): StateProxy<T>

// return the object reference to the initialValue
export function unProxy<T extends object>(proxy: StateProxy<T>): T

Features

  • [x] Auto trigger re-render when invoking mutating methods on state fields
    • [x] Array
    • [x] Map
    • [x] Set
    • [x] Date
    • [x] Object
    • [X] Custom Classes
  • [ ] Create a variant for shared state, as simpler alternative to redux store (using redux or context)
  • [x] Tested with @testing-library/jest-dom

Comparison

With use-state-proxy

You can get/set the values, and call mutating methods (e.g. array.push()) directly.

The 'setState' action is auto dispatched when the value is changed, which auto trigger re-rendering.

Usage Example:

import React from 'react'
import { useStateProxy } from 'use-state-proxy'

function DemoUseStateProxy() {
  const state = useStateProxy({
    text: '',
    list: ['init']
  })
  const { list } = state
  return <>
    <input
      value={state.text}
      onChange={e => state.text = e.target.value}
    />
    <button onClick={() => {
      list.push(state.text);
      state.text = '';
    }}>
      Save
    </button>
    <ul>
      {list.map((item, i) => <li key={i}>
        <button onClick={() => list.splice(i, 1)}>Delete</button>
        <span>{item}</span>
        <input
          value={item}
          onChange={(e) => {
            state.list[i] = e.target.value
            state.list = state.list
          }}
        />
      </li>)}
    </ul>
  </>
}

export default DemoUseStateProxy

Using useStateProxy(), the array can be updated with state.list.push(state.text) and state.list.splice(i, 1) directly. This invokes proxied methods, and it will auto trigger re-rendering.

Without use-state-proxy

You need to set up the states one-by-one, and explicitly call the setHooks to trigger re-rendering.

Moreover, there is syntax noise when updating complex data type, e.g. Array, Map, Set, and Object.

import React, { useState } from 'react'

function DemoUseState() {
  const [text, setText] = useState('')
  const [list, setList] = useState(['init'])
  return <>
    <input value={text} onChange={e => setText(e.target.value)} />
    <button
      onClick={() => {
        setList([...list, text]);
        setText('');
      }}
    >
      Save
    </button>
    <ul>
      {list.map((item, i) => <li key={i}>
        <button onClick={() => setList(list.filter((_, j) => i !== j))}>
          Delete
        </button>
        <span>{item}</span>
        <input
          value={item}
          onChange={(e) => {
            const newList = [...list];
            newList[i] = e.target.value;
            setList(newList);
          }}
        />
      </li>)}
    </ul>
  </>
}

export default DemoUseState

In this example, in order to 'push' an item to the list, it manually destructs the original array with spread syntax ... then append the new item at the end.

Also, to remove an item from the list, it constructs a new array with list.filter(), involving multiple levels of array indices, which is error-prone.

The same hurdles applies to object as well, and it gets even worse when it comes to Set* and Map**.

*: To update a Set, we can run setList(new Set([...list, item])) or setList(new Set([...list].filter(x => x !== target)))

**: To update a Map, we can run setList(new Map([...list, [key, value]])) or setList(new Map([...list].filter(([key]) => key !== target)))

Register Mutating Methods on Custom Classes

The mutating methods of custom classes can be registered. This mechanism allows use-state-proxy to auto trigger re-rendering even when the state consists of non-json values. (Array, Map, Set and Date are supported by default.)

Below demo how to register mutating methods on WeakSet with registerMutableMethodsByClassConstructor() and registerMutableMethodsByClassName():

import {
  registerMutableMethodsByClassConstructor,
  registerMutableMethodsByClassName
} from 'use-state-proxy'

let mutableWeakSetMethods: Array<keyof typeof WeakSet.prototype> = [
  'add',
  'delete',
]
registerMutableMethodsByClassConstructor(WeakSet, methods)
registerMutableMethodsByClassName('[object WeakSet]', methods) // to support cross-frame objects

You can also use helper functions getClassName() and registerPrimitiveMutableClass() to avoid typo mistakes.

import { getClassName, registerPrimitiveMutableClass } from 'use-state-proxy'

registerPrimitiveMutableClass(WeakSet, getClassName(new WeakSet()), ['add', 'delete'])

Details see demo-custom-mutable-class.ts

Todo

  • [ ] Refactor into typical react-library structure https://medium.com/better-programming/build-your-very-own-react-component-library-and-publish-it-to-github-package-registry-192a688a51fd

License

BSD-2-Clause (Free Open Source Software)