Skip to content

Commit

Permalink
fix: πŸ› dont memoize useScratch event handlers
Browse files Browse the repository at this point in the history
  • Loading branch information
streamich committed May 17, 2020
1 parent 15a1d9a commit ffc7579
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 10 deletions.
9 changes: 9 additions & 0 deletions src/useLatest.ts
Original file line number Diff line number Diff line change
@@ -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;
18 changes: 8 additions & 10 deletions src/useScratch.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { useState, useEffect, useRef, FC, cloneElement } from 'react';
import { render } from 'react-universal-interface';
import useLatest from './useLatest';

const noop = () => {};

Expand Down Expand Up @@ -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);
Expand All @@ -60,7 +58,7 @@ const useScratch = ({
isScratching: true,
};
refState.current = newState;
onScratch(newState);
(paramsRef.current.onScratch || noop)(newState);
return newState;
});
});
Expand All @@ -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);
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -152,7 +150,7 @@ const useScratch = ({
refState.current = { isScratching: false };
setState(refState.current);
};
}, [el, disabled, onScratchStart, onScratch, onScratchEnd]);
}, [el, disabled, paramsRef]);

return [setEl, state];
};
Expand Down

0 comments on commit ffc7579

Please sign in to comment.