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

react-immutable-state-controller

v1.0.1

Published

React hooks for the Immutable state change controller

Downloads

16

Readme

React Immutable State Controller

npm version Node CI

A small library to manage immutable state in a tree of React components without a lot of boilerplate, but with a lot of type-safety.

Installation

npm install react-immutable-state-controller

Raison d’être

A difficulty with React’s useState (or component state in pre-hooks world) is that changes to state are not visible to code until the component re-renders. This is a difficulty because it can lead to mistakes due to misunderstandings — it’s odd that value isn’t immediately changed after you’ve called setValue — and a strength because immutability makes code safer and is fundamental to React.

Another difficulty with React’s useState is that the entire component subtree re-renders when the state changes. This is annoying if you have a component managing a large state object and delegating the modification of parts of that state to child components.

Compared to Redux

Redux provides a similar capability to react-immutable-state-controller, however with a lot more complexity and boilerplate. Also Redux is designed to manage global state in an application, where you really benefit from using reducers, selectors and actions, whereas react-immutable-state-controller is designed to improve the managing of local state in a tree of components.

Solution

With react-immutable-state-controller you create one or more controllers to contain state in a component, or at the root of a tree of components that use that state. Using the controller you can get and set parts of its state, with re-renders limited to components that use the part of the state that has changed (using useSnapshot).

The useSnapshot hook works a little like React’s useState, except instead of creating a state value that’s local to the component, it always reflects and updates the value in the controller, where that controller has possibly been created in the current component or passed as props from a parent component.

Example

interface Person {
	name: Name
	address: Address
}

interface Name {
	givenName: string
	middleName?: string
	familyName: string
}

interface Address {
	street: string
}

function EditPersonComponent({ person: Person; onChange: (newPerson: Person) => void }) {
	const controller = useNewController(person)

	const handleSave = useCallback(function(evt: React.MouseEvent) {
		evt.preventDefault()
		onChange(controller.value)
	}, [controller])

	return (
		<>
		<EditName controller={controller.get('name')} />
		<EditAddress controller={controller.get('address')} />
		<button onClick={handleSave}>Save</button>
		</>
	)
}

function EditName(props: { controller: Controller<Name> }) {
	const [givenName, changeGivenName] = useSnapshot(controller)
	const [middleName, changeMiddleName] = useSnapshot(controller)
	const [familyName, changeFamilyName] = useSnapshot(controller)

	const handleGivenName = useCallback(function(evt: React.ChangeEvent<HTMLInputElement>) {
		changeGivenName(evt.target.value)
	}, [changeGivenName])

	return (
		<input type="text" value={givenName} onChange={handleGivenName} />
	)
}

In this example the EditPersonComponent will not re-render even though the givenName property is changing in the controller.

Immutability

Controllers use immer to ensure the immutability of the values they contain. The values that you get from a controller or snapshot will be immutable (frozen), so if you’re mutating an array or object value, you’ll need to use immer’s produce method to mutate it, or spread / copy it.

Hooks

useNewController

useNewController(initialValue) returns a new Controller that controls access to the state; whatever type that is.

The Controller has a value property to access the current state, and a setValue function to change that state. Changes to the Controller’s value are immediately visible in code, but they DO NOT trigger a re-render in React.

A useNewController hook always returns the same Controller object, so passing a controller to child components will not cause a re-render even if the value in the controller has changed. That's why you need useSnapshot to re-render when state changes...

useController

useController(controller) simply returns the given controller, but it will trigger re-renders when the value in the controller changes. useController is useful if you're using the Controller's map, find or findIndex methods and therefore need to re-render if the controller's value changes.

useSnapshot

useSnapshot(controller) and useSnapshot(controller, property) returns an array containing the current value (immutable) and a function to change the value (exactly like React’s useState).

The value originates from the Controller; either the whole value of the controller or one of its properties.

If the value is changed, either using useSnapshot’s change function, or any other snapshot’s change function, or even using the Controller’s own setValue function, the component WILL re-render.

Reference

See immutable-state-controller for more information and an API reference for Controllers and Snapshots.