Merge pull request #1217 from streamich/fix-useScratch

fix: 🐛 dont memoize useScratch event handlers
This commit is contained in:
Vadim Dalecky 2020-05-18 01:10:02 +02:00 committed by GitHub
commit 7baf40bb56
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 17 additions and 10 deletions

9
src/useLatest.ts Normal file
View 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;

View File

@ -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];
};