Skip to content

Instantly share code, notes, and snippets.

@GarryOne
Created December 13, 2022 21:05
Show Gist options
  • Save GarryOne/53a191dd6ebb385461f57c177592eefd to your computer and use it in GitHub Desktop.
Save GarryOne/53a191dd6ebb385461f57c177592eefd to your computer and use it in GitHub Desktop.
React Memo comparison deep objects using JSON.stringify()
export const isPrimitive = (val) => {
if (val === null) {
return true;
}
if (typeof val === "object" || typeof val === "function") {
return false;
} else {
return true;
}
};
export const omitNotPrimitiveProps = (row) => {
const _row = {};
Object.keys(row).map((key) => {
if (isPrimitive(row[key])) {
_row[key] = row[key];
}
});
return _row;
};
// Usage example
export default memo(DataTable, (prevProps, nextProps) => {
const { table: prevTableProp, ...prevPrimitiveProps } = prevProps;
const { table: nextTableProp, ...nextPrimitiveProps } = nextProps;
const primitivePropsAreEqual =
JSON.stringify(omitNotPrimitiveProps(prevPrimitiveProps)) ===
JSON.stringify(omitNotPrimitiveProps(nextPrimitiveProps));
const tableColumnsAreEqual =
JSON.stringify(prevTableProp.columns) ===
JSON.stringify(nextTableProp.columns);
const tableRowsAreEqual =
JSON.stringify(prevTableProp.rows.map(omitNotPrimitiveProps)) ===
JSON.stringify(nextTableProp.rows.map(omitNotPrimitiveProps));
return primitivePropsAreEqual && tableColumnsAreEqual && tableRowsAreEqual;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment