react-shallow-context

A speed optimization for a Context API

Downloads in past

Stats

StarsIssuesVersionUpdatedCreatedSize
react-shallow-context
11701.0.16 years ago6 years agoMinified + gzip package size for react-shallow-context in KB

Readme


Goal
This package optimizes React.Context API, implementing calculateChangedBits, which works the same way shouldComponentUpdate or just PureComponent works - optimizes the way React react to updated
The problem
It is common to store something inside context Provider. Something like this
<Provider value={{key1: 1, key2: 2}} />
That would produce a new value every time, causing all Consumers to update, and causing React to traverse all the tree, to find those Consumers. This package provides a way to handle the value change event, and suppress unnecessary updates.
API

createPureContext(defaultValue)

Creates "pure" context, the same "pure" as in "PureComponent". This is basically React.createContext(xx, pureContextCompare)

pureContextCompare

shallow compares the old and the next context value. Supress update if the are the same.
import {pureContextCompare} from 'react-shallow-context';
const context = React.createContext({}, pureContextCompare);

// equal to
const context = createPureContext({});
``` 

## updateIgnoring(keys)
The same, but ignoring selected keys. Useful then context contain some `callback` function, which could be allways the different, 
but play a role, only when anther value got changed. 
```js
import {updateIgnoring} from 'react-shallow-context';
const context = React.createContext({importantValue, notImportantValue}, updateIgnoring(['notImportantValue']));

updateOnlyFor(keys)

The same, but with inversed logic.
import {updateOnlyFor} from 'react-shallow-context';
const context = React.createContext({importantValue, notImportantValue}, updateOnlyFor(['importantValue']));
Written in TypeScript
Licence
MIT