memcord
Record objects that return reference-equal values when you repeat previous updates.
Install with npm install memcord --save
.
// Create a new record with the given valuesconst model = // Access values like a normal recordconsole // koala // Repeatedly setting the same value will return reference-equal objects.const newRecord1 = modelconst newRecord2 = model console // koalaconsole // kangarooconsole // kangaroo console // true
Why?
Memcords let you use records as React props, without breaking PureComponent
.
In large React applications, it is important for performance that your props can be compared by reference equality. Without reference equality, PureComponent
can't provide any performance wins -- making performance optimization a much harder problem.
Primitive props (i.e. strings and numbers) will always work as expected, making them easy to use. However, objects present a problem; if you want to update an immutable object in each render
cycle, they'll never be reference-equal -- even if their values are equivalent!
const model = value: 'kangaroo' const newModel1 = value: 'koala' const newModel2 = value: 'koala' console // false!
Memcords detect repeated changes and return identical values, simplifying the use of records as props.
// Create new record with the given valuesconst model = // Repeatedly setting the same value will return reference-equal objects.const newRecord1 = modelconst newRecord2 = model console //true
Usage
createMemcord(values, equals?)
Create a memoized record.
You can also customize how the memcord checks for equality by passing in a comparison function as the second argument. By default, it will use reference equality.
const data = console // 'kangaroo'console // undefined const nextData = // Two memcords created with separate calls to `createMemcord`// will never be equal, even if they share the same properties.console // false
set(key, value)
Set values with set
. Repeating the same set
will return the same record.
const newData1 = data console // 'dropbear'console // true const newData2 = data console // 'dropbear'console // true
merge(values)
You update multiple value at a time with merge
.
const merged1 = data console // 'giant koala'console // 'extinct' const merged2 = data console // true