1.0.0 • Published 4 years ago

use-reusable-state v1.0.0

Weekly downloads
2
License
MIT
Repository
github
Last release
4 years ago

npm version downloads build status coverage status Language grade: JavaScript

use-reusable-state

This package provides a custom React hook useReusableState which has the same interface as useState, but if the data provided in the setter is deep-equal to the current value, the current value will be re-used, and no re-render will be triggered. If the data is not deep-equal, the data will be set, but it will be recursively checked for deep-equality so that sub-properties will be re-used if possible. This might cause less re-renderings in a deep React component tree.

Uses instead for deep-equality and partial replacement.

Usage

yarn add use-reusable-state
import useReusableState from 'use-reusable-state'

const [ value, setValue ] = useReusableState( /* init */ { foo: 'bar' } );

// Sets a new value, but it's deep-equal to the current value,
// so no re-rendering will be triggered.
setValue( { foo: 'bar' } );

// Sub-property changed, so the new object will be saved.
setValue( { foo: 'baz' } );

Deep re-using

const [ value, setValue ] = useReusableState( /* init */ {
	a: { foo: 'bar' },
	b: { foo: 'bar' },
} );

// Sets a new value, where a property is deep-equal to the current value.
// Will cause re-rendering
setValue( {
	a: { foo: 'bar' }, // Same as before
	b: { foo: 'baz' }, // Only b changed
} );

// ...
// The next iteration:
// ...

const [ value2, _ ] = useReusableState( /* ... */ );

value2.a === value.a; // true; referencial equality, the object was _reused_
value2.b !== value.b; // true; new object
value2 !== value;     // true; any change in the tree triggers a new parent