Skip to content

Instantly share code, notes, and snippets.

@nirajrajgor
Created January 19, 2021 09:37
Show Gist options
  • Save nirajrajgor/d75307b125afea8a30facbad700e485a to your computer and use it in GitHub Desktop.
Save nirajrajgor/d75307b125afea8a30facbad700e485a to your computer and use it in GitHub Desktop.
React.memo native implementation (Polyfill)(Asked in Interview)
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