Created
January 19, 2021 09:37
-
-
Save nirajrajgor/d75307b125afea8a30facbad700e485a to your computer and use it in GitHub Desktop.
React.memo native implementation (Polyfill)(Asked in Interview)
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
const shallowCompare = (prev, next) => { | |
for (let key in next) { | |
if (next[key] !== prev[key]) return false; | |
} | |
return true; | |
}; | |
export function memo(Component, areEqual = shallowCompare) { | |
let prevProps = {}; | |
let prevResult = JSX.Element | undefined; | |
return (nextProps) => { | |
if (prevResult !== undefined && areEqual(prevProps, nextProps)) { | |
return prevResult; | |
} | |
prevProps = nextProps; | |
prevResult = <Component {...nextProps} />; | |
return prevResult; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment