React Shallow Context Save

☘️A speed optimization for a Context API

Project README

React Shallow Context


Pure shallow equal for update propagation in 300b.

Goal

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.

The problem

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.

API

createPureContext(defaultValue)

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();

pureContextCompare

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({});

updateIgnoring(keys)

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']));

updateOnlyFor(keys)

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']));

Licence

MIT

Open Source Agenda is not affiliated with "React Shallow Context" Project. README Source: theKashey/react-shallow-context
Stars
118
Open Issues
0
Last Commit
5 years ago
License
MIT

Open Source Agenda Badge

Open Source Agenda Rating