This package optimizes React.Context API by implementing calculateChangedBits
, which works the same way as
shouldComponentUpdate
or PureComponent
- it optimizes the way React reacts to context updates.
It is common to store an object inside of the context Provider
:
<Provider value={{key1: 1, key2: 2}} />
However, that produces a new value
every time, causing all Consumers
to update. React then needs to traverse
the entire tree to find those Consumer
components.
This package provides a way to handle when the value changes, and suppress unnecessary updates.
Creates "pure" context, the same way that "PureComponent" is "pure." This is equivalent to React.createContext(xx, pureContextCompare)
👎 import {createContext} from 'react';
const context = createContext();
👍 import {createPureContext} from 'react-shallow-context';
const context = createPureContext();
Shallow compares the old and next context value. It supresses the update if they are the same.
import {pureContextCompare} from 'react-shallow-context';
const context = React.createContext({}, pureContextCompare);
// equal to
const context = createPureContext({});
The same as pureContextCompare
, but it ignores selected keys. This is useful when the context contains some callback
function that could always be different,
but only plays a role when another value is changed.
import {updateIgnoring} from 'react-shallow-context';
const context = React.createContext({importantValue, notImportantValue}, updateIgnoring(['notImportantValue']));
The inverse of updateIgnoring
. Will only trigger an update when the given keys
change.
import {updateOnlyFor} from 'react-shallow-context';
const context = React.createContext({importantValue, notImportantValue}, updateOnlyFor(['importantValue']));
MIT