https://github.com/thekashey/react-shallow-context
☘️A speed optimization for a Context API
https://github.com/thekashey/react-shallow-context
context-api purecomponent react shallow-equal
Last synced: 5 months ago
JSON representation
☘️A speed optimization for a Context API
- Host: GitHub
- URL: https://github.com/thekashey/react-shallow-context
- Owner: theKashey
- License: mit
- Created: 2018-10-04T00:28:34.000Z (over 7 years ago)
- Default Branch: master
- Last Pushed: 2019-05-04T22:33:27.000Z (almost 7 years ago)
- Last Synced: 2025-01-13T03:50:19.675Z (about 1 year ago)
- Topics: context-api, purecomponent, react, shallow-equal
- Language: TypeScript
- Homepage:
- Size: 147 KB
- Stars: 117
- Watchers: 3
- Forks: 2
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# 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`:
```js
```
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)`
```js
👎 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.
```js
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.
```js
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.
```js
import {updateOnlyFor} from 'react-shallow-context';
const context = React.createContext({importantValue, notImportantValue}, updateOnlyFor(['importantValue']));
```
# Licence
MIT