Skip to content

Commit

Permalink
cancel animation frame on un-mount
Browse files Browse the repository at this point in the history
  • Loading branch information
wardoost committed Mar 23, 2019
1 parent 71eb416 commit 584bd7e
Showing 1 changed file with 11 additions and 8 deletions.
19 changes: 11 additions & 8 deletions src/useScroll.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,35 +11,38 @@ const useScroll = (ref): State => {
const [state, setState] = useState<State>({
x: isClient ? window.scrollX : 0,
y: isClient ? window.scrollY : 0
})
});

useEffect(() => {
const handler = () => {
cancelAnimationFrame(frame.current)

frame.current = requestAnimationFrame(() => {
setState({
x: ref.current.scrollLeft,
y: ref.current.scrollTop
})
})
});
});
}

if (ref && ref.current) {
ref.current.addEventListener('scroll', handler, {
capture: false,
passive: true
})
});
}

return () => {
if (frame.current) {
cancelAnimationFrame(frame.current);
}

if (ref && ref.current) {
ref.current.removeEventListener('scroll', handler)
ref.current.removeEventListener('scroll', handler);
}
};
}, [ref])
}, [ref]);

return state
return state;
}

export default useScroll

0 comments on commit 584bd7e

Please sign in to comment.