set-state-compare
v1.0.74
Published
setState for React that compares with the current state and only sets the state if changed.
Readme
set-state-compare
Lightweight helpers for React state updates, shape-style state containers, and value comparison utilities.
Install
npm install set-state-compareExports
import {
anythingDifferent,
arrayDifferent,
arrayReferenceDifferent,
isSimpleObject,
referenceDifferent,
simpleObjectDifferent,
simpleObjectValuesDifferent,
Shape,
setState
} from "set-state-compare"State Helpers
setState
Drop-in helper that only applies state updates when values actually change.
import setState from "set-state-compare"
await setState(this, {count: 1})Shape
Class-based state container with batched rendering support.
import {Shape} from "set-state-compare"
const shape = new Shape(component)
shape.set({count: 1}, () => {
// called after render
})Modes:
Shape.setMode("queuedForceUpdate")usesforceUpdatewith an after-paint queue.Shape.setMode("setState")usessetStateon the component.
ShapeComponent
Class-style component wrapper with hooks-friendly state helpers.
setup() runs before each render, so initialization in setup() is re-applied every render. It is also the recommended place to call hook-style helpers like useState/useStates.
import {ShapeComponent, shapeComponent} from "set-state-compare/build/shape-component.js"
class Counter extends ShapeComponent {
render() {
this.useState("count", 0)
return React.createElement("div", null, String(this.state.count))
}
}
export default shapeComponent(Counter)cache
Instance-level cache with dependency comparison.
const style = this.cache("style", () => ({padding: 8}), [theme, size])cacheStatic
Class-level cache shared across instances.
const config = this.cacheStatic("config", () => ({padding: 8}), [theme, size])useShape
Hook-style shape for function components.
import useShape from "set-state-compare/build/use-shape.js"
function Example(props) {
const shape = useShape(props)
shape.useState("count", 0)
return React.createElement("div", null, String(shape.state.count))
}useShapeHook
Class-based hooks with ShapeComponent-style lifecycle methods like setup, componentDidMount, and componentWillUnmount.
import useShapeHook, {ShapeHook} from "set-state-compare/build/shape-hook.js"
class MyShapeHookClass extends ShapeHook {
setup() {
this.useState("count", 0)
}
}
function Example(props) {
const shapeHook = useShapeHook(MyShapeHookClass, props)
return React.createElement("div", null, String(shapeHook.state.count))
}Comparison Utilities
anythingDifferentdeep-compares arrays and simple objects.referenceDifferentuses reference comparison for objects/arrays andObject.isfor primitives.arrayReferenceDifferentcompares array lengths and each element withreferenceDifferent.simpleObjectDifferentandsimpleObjectValuesDifferentcompare plain objects.arrayDifferentcompares arrays by value.isSimpleObjectchecks for plain objects (ignores React internal objects).
Tests
npm test
npm run typecheck