mirror of
https://github.com/streamich/react-use.git
synced 2026-01-18 14:06:52 +00:00
Merge pull request #1217 from streamich/fix-useScratch
fix: 🐛 dont memoize useScratch event handlers
This commit is contained in:
commit
7baf40bb56
9
src/useLatest.ts
Normal file
9
src/useLatest.ts
Normal file
@ -0,0 +1,9 @@
|
||||
import {useRef} from 'react';
|
||||
|
||||
const useLatest = <T>(value: T): {readonly current: T} => {
|
||||
const ref = useRef(value);
|
||||
ref.current = value;
|
||||
return ref;
|
||||
};
|
||||
|
||||
export default useLatest;
|
||||
@ -1,5 +1,6 @@
|
||||
import { useState, useEffect, useRef, FC, cloneElement } from 'react';
|
||||
import { render } from 'react-universal-interface';
|
||||
import useLatest from './useLatest';
|
||||
|
||||
const noop = () => {};
|
||||
|
||||
@ -28,12 +29,9 @@ export interface ScratchSensorState {
|
||||
elY?: number;
|
||||
}
|
||||
|
||||
const useScratch = ({
|
||||
disabled,
|
||||
onScratch = noop,
|
||||
onScratchStart = noop,
|
||||
onScratchEnd = noop,
|
||||
}: ScratchSensorParams = {}): [(el: HTMLElement | null) => void, ScratchSensorState] => {
|
||||
const useScratch = (params: ScratchSensorParams = {}): [(el: HTMLElement | null) => void, ScratchSensorState] => {
|
||||
const {disabled} = params;
|
||||
const paramsRef = useLatest(params);
|
||||
const [state, setState] = useState<ScratchSensorState>({ isScratching: false });
|
||||
const refState = useRef<ScratchSensorState>(state);
|
||||
const refScratching = useRef<boolean>(false);
|
||||
@ -60,7 +58,7 @@ const useScratch = ({
|
||||
isScratching: true,
|
||||
};
|
||||
refState.current = newState;
|
||||
onScratch(newState);
|
||||
(paramsRef.current.onScratch || noop)(newState);
|
||||
return newState;
|
||||
});
|
||||
});
|
||||
@ -81,7 +79,7 @@ const useScratch = ({
|
||||
if (!refScratching.current) return;
|
||||
refScratching.current = false;
|
||||
refState.current = { ...refState.current, isScratching: false };
|
||||
onScratchEnd(refState.current);
|
||||
(paramsRef.current.onScratchEnd || noop)(refState.current);
|
||||
setState({ isScratching: false });
|
||||
window.removeEventListener('mousemove', onMouseMove);
|
||||
window.removeEventListener('touchmove', onTouchMove);
|
||||
@ -116,7 +114,7 @@ const useScratch = ({
|
||||
elY,
|
||||
};
|
||||
refState.current = newState;
|
||||
onScratchStart(newState);
|
||||
(paramsRef.current.onScratchStart || noop)(newState);
|
||||
setState(newState);
|
||||
window.addEventListener('mousemove', onMouseMove);
|
||||
window.addEventListener('touchmove', onTouchMove);
|
||||
@ -152,7 +150,7 @@ const useScratch = ({
|
||||
refState.current = { isScratching: false };
|
||||
setState(refState.current);
|
||||
};
|
||||
}, [el, disabled, onScratchStart, onScratch, onScratchEnd]);
|
||||
}, [el, disabled, paramsRef]);
|
||||
|
||||
return [setEl, state];
|
||||
};
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user