UNPKG

1.05 kBJavaScriptView Raw
1import { createElement } from 'preact';
2import { shallowDiffers } from './util';
3
4/**
5 * Memoize a component, so that it only updates when the props actually have
6 * changed. This was previously known as `React.pure`.
7 * @param {import('./internal').FunctionComponent} c functional component
8 * @param {(prev: object, next: object) => boolean} [comparer] Custom equality function
9 * @returns {import('./internal').FunctionComponent}
10 */
11export function memo(c, comparer) {
12 function shouldUpdate(nextProps) {
13 let ref = this.props.ref;
14 let updateRef = ref == nextProps.ref;
15 if (!updateRef && ref) {
16 ref.call ? ref(null) : (ref.current = null);
17 }
18
19 if (!comparer) {
20 return shallowDiffers(this.props, nextProps);
21 }
22
23 return !comparer(this.props, nextProps) || !updateRef;
24 }
25
26 function Memoed(props) {
27 this.shouldComponentUpdate = shouldUpdate;
28 return createElement(c, props);
29 }
30 Memoed.displayName = 'Memo(' + (c.displayName || c.name) + ')';
31 Memoed.prototype.isReactComponent = true;
32 Memoed._forwarded = true;
33 return Memoed;
34}