Skip to content

Commit

Permalink
Prevent re-installing effect on re-render when start and end are new …
Browse files Browse the repository at this point in the history
…objects with the same values
  • Loading branch information
Peeke Kuepers committed Feb 16, 2023
1 parent f220af0 commit 27eaba7
Showing 1 changed file with 31 additions and 3 deletions.
34 changes: 31 additions & 3 deletions src/react.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,20 +12,48 @@ export function useScrollProgression({
const onChangeRef = React.useRef(null)
onChangeRef.current = onChange

const stableStart = useStableObject(start)
const stableEnd = useStableObject(end)

React.useEffect(
() => {
if (!node) return

return onScrollProgression({
element: node,
start,
end,
start: stableStart,
end: stableEnd,
clamp,
onChange(...args) { onChangeRef.current(...args) }
})
},
[node, start, end, clamp]
[node, stableStart, stableEnd, clamp]
)

return setNode
}

function useStableObject(object) {
const objectRef = React.useRef(object)

if (!isDeepCopy(object, objectRef.current)) {
objectRef.current = object
}

return objectRef.current
}

function isDeepCopy(source, target) {
if(typeof source !== typeof target) return false

if(Array.isArray(source) && Array.isArray(target)){
if(source.length !== target.length) return false
return source.every((value, index) => isDeepCopy(value, target[index]))
}

if(typeof source === 'object' && typeof target === 'object') {
return Object.keys(source).every((key) => isDeepCopy(source[key], target[key]))
}

return source === target
}

0 comments on commit 27eaba7

Please sign in to comment.