mirror of
https://github.com/facebook/docusaurus.git
synced 2025-07-07 11:57:55 +02:00
perf(v2): reduce amount of navbar renders while scrolling (#4473)
This commit is contained in:
parent
af840b7f85
commit
f12e8b596d
4 changed files with 17 additions and 23 deletions
|
@ -5,7 +5,7 @@
|
|||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import {useState, useEffect} from 'react';
|
||||
import {useEffect, useRef} from 'react';
|
||||
import ExecutionEnvironment from '@docusaurus/ExecutionEnvironment';
|
||||
import type {ScrollPosition} from '@theme/hooks/useScrollPosition';
|
||||
|
||||
|
@ -15,19 +15,19 @@ const getScrollPosition = (): ScrollPosition => ({
|
|||
});
|
||||
|
||||
const useScrollPosition = (
|
||||
effect?: (position: ScrollPosition) => void,
|
||||
effect?: (position: ScrollPosition, lastPosition: ScrollPosition) => void,
|
||||
deps = [],
|
||||
): ScrollPosition => {
|
||||
const [scrollPosition, setScrollPosition] = useState(getScrollPosition());
|
||||
): void => {
|
||||
const scrollPosition = useRef(getScrollPosition());
|
||||
|
||||
const handleScroll = () => {
|
||||
const currentScrollPosition = getScrollPosition();
|
||||
|
||||
setScrollPosition(currentScrollPosition);
|
||||
|
||||
if (effect) {
|
||||
effect(currentScrollPosition);
|
||||
effect(currentScrollPosition, scrollPosition.current);
|
||||
}
|
||||
|
||||
scrollPosition.current = currentScrollPosition;
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
|
@ -35,12 +35,11 @@ const useScrollPosition = (
|
|||
passive: true,
|
||||
};
|
||||
|
||||
handleScroll();
|
||||
window.addEventListener('scroll', handleScroll, opts);
|
||||
|
||||
return () => window.removeEventListener('scroll', handleScroll, opts);
|
||||
}, deps);
|
||||
|
||||
return scrollPosition;
|
||||
};
|
||||
|
||||
export default useScrollPosition;
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue