Created
December 13, 2022 21:05
-
-
Save GarryOne/53a191dd6ebb385461f57c177592eefd to your computer and use it in GitHub Desktop.
React Memo comparison deep objects using JSON.stringify()
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
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