Skip to content

Commit

Permalink
fix: improve performance by adding enabled flag to useWatcher (#196)
Browse files Browse the repository at this point in the history
- we only need to register the measuring callback if we actually have a `node` prop.
- this reduced a lot of unnecessary computations that made applications with a lot of `Stick` components slow over time.

Co-authored-by: Andreas Köberle <koeberle@gmail.com>

Co-authored-by: Andreas Köberle <koeberle@gmail.com>
  • Loading branch information
tzimmermann and eskimoblood committed Nov 6, 2020
1 parent 5be7027 commit a063a26
Show file tree
Hide file tree
Showing 3 changed files with 6 additions and 5 deletions.
2 changes: 1 addition & 1 deletion src/Stick.js
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ function Stick({
}
}, [resolvedAlign, resolvedPosition, sameWidth, width])

useWatcher(measure, { updateOnAnimationFrame })
useWatcher(measure, {updateOnAnimationFrame, enabled: !!node} )

const handleReposition = useCallback(() => {
if (nodeRef.current && anchorRef.current) {
Expand Down
2 changes: 1 addition & 1 deletion src/StickPortal.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ function StickPortal(
}
}, [host, left, position, top, visible])

useWatcher(measure, { updateOnAnimationFrame })
useWatcher(measure, { updateOnAnimationFrame, enabled: visible })

const Component = component || 'div'
return (
Expand Down
7 changes: 4 additions & 3 deletions src/hooks/useWatcher.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,19 @@ import { useEffect } from 'react'
type WatcherFuncT = () => void
type OptionsT = {|
updateOnAnimationFrame: boolean,
enabled: boolean
|}

function useWatcher(
watcher: WatcherFuncT,
{ updateOnAnimationFrame }: OptionsT
{ updateOnAnimationFrame, enabled }: OptionsT
): void {
useEffect(() => {
let animationFrameId
let idleCallbackId

// do not track in node
if (typeof window.requestAnimationFrame !== 'undefined') {
if (enabled && typeof window.requestAnimationFrame !== 'undefined') {
const callback = () => {
watcher()

Expand All @@ -38,7 +39,7 @@ function useWatcher(
cancelIdleCallback(idleCallbackId)
}
}
}, [updateOnAnimationFrame, watcher])
}, [updateOnAnimationFrame, watcher, enabled])
}

export default useWatcher

1 comment on commit a063a26

@vercel
Copy link

@vercel vercel bot commented on a063a26 Nov 6, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.