Skip to content

Instantly share code, notes, and snippets.

@mohdovais
Last active August 14, 2019 09:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mohdovais/2eaf66d00c5fe495647ea1cc152034dc to your computer and use it in GitHub Desktop.
Save mohdovais/2eaf66d00c5fe495647ea1cc152034dc to your computer and use it in GitHub Desktop.
naive React v15 pure functional component
import React from 'react';
const pureMap = new WeakMap();
function makeComponent(fn, compare) {
return class Memo extends React.Component {
shouldComponentUpdate(nextProps) {
return compare(this.props, nextProps);
}
render() {
return fn(this.props);
}
};
}
function makePureComponent(fn) {
return class Memo extends React.Component {
render() {
return fn(this.props);
}
};
}
function makePure(fn, compare) {
const { propTypes } = fn;
const component = typeof compare === 'function'
? makeComponent(fn, compare)
: makePureComponent(fn);
Object.defineProperty(component, 'name', { value: `Memo(${fn.name})` });
if (propTypes !== undefined) {
component.propTypes = propTypes;
}
return component;
}
export function pure(fn, compare) {
if (!pureMap.has(fn)) {
pureMap.set(fn, makePure(fn, compare));
}
return pureMap.get(fn);
}
@mohdovais
Copy link
Author

Usage

import React from 'react';
import PropTypes from 'prop-types';
import { pure } from './pure';

function MyComponent(props){
    return <h1>{props.title}</h1>;
}

MyComponent.propTypes = {
    title: PropTypes.string
}

export default pure(MyComponent);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment