From ffc75790e329cb26000a174074c07d80283b5443 Mon Sep 17 00:00:00 2001 From: streamich Date: Mon, 18 May 2020 01:04:41 +0200 Subject: [PATCH] =?UTF-8?q?fix:=20=F0=9F=90=9B=20dont=20memoize=20useScrat?= =?UTF-8?q?ch=20event=20handlers?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/useLatest.ts | 9 +++++++++ src/useScratch.ts | 18 ++++++++---------- 2 files changed, 17 insertions(+), 10 deletions(-) create mode 100644 src/useLatest.ts diff --git a/src/useLatest.ts b/src/useLatest.ts new file mode 100644 index 00000000..f7386758 --- /dev/null +++ b/src/useLatest.ts @@ -0,0 +1,9 @@ +import {useRef} from 'react'; + +const useLatest = (value: T): {readonly current: T} => { + const ref = useRef(value); + ref.current = value; + return ref; +}; + +export default useLatest; diff --git a/src/useScratch.ts b/src/useScratch.ts index 2f73530a..6703d348 100644 --- a/src/useScratch.ts +++ b/src/useScratch.ts @@ -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({ isScratching: false }); const refState = useRef(state); const refScratching = useRef(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]; };