Last active
August 14, 2019 09:03
-
-
Save mohdovais/2eaf66d00c5fe495647ea1cc152034dc to your computer and use it in GitHub Desktop.
naive React v15 pure functional component
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage