Skip to content

Instantly share code, notes, and snippets.

@sivcan
Created March 7, 2018 11:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sivcan/e4dbeb1efcc4ffbc648d492e19506972 to your computer and use it in GitHub Desktop.
Save sivcan/e4dbeb1efcc4ffbc648d492e19506972 to your computer and use it in GitHub Desktop.
React utility for nextProps diff (Shallow check)
// Use it with the componentWillReceiveProps lifecycle method
//
// componentWillReceiveProps(nextProps) {
// shallowEqual(this.props, nextProps);
// }
//
function shallowEqual(objA, objB) {
if (is(objA, objB)) return true
if (typeof objA !== "object" || objA === null || typeof objB !== "object" || objB === null) {
return false
}
const keysA = Object.keys(objA)
const keysB = Object.keys(objB)
if (keysA.length !== keysB.length) return false
for (let i = 0; i < keysA.length; i++) {
if (!hasOwnProperty.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) {
console.log(keysA[i]);
return false
}
}
return true
}
function is(x, y) {
if (x === y) {
return x !== 0 || 1 / x === 1 / y
} else {
return x !== x && y !== y
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment