Skip to content

Commit

Permalink
Keep a ref of point value to obviate effect hook
Browse files Browse the repository at this point in the history
  • Loading branch information
stokesman committed Jul 12, 2022
1 parent 998ce0a commit 832ea2c
Showing 1 changed file with 9 additions and 13 deletions.
22 changes: 9 additions & 13 deletions packages/components/src/focal-point-picker/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,18 +46,18 @@ export default function FocalPointPicker( {
},
} ) {
const [ point, setPoint ] = useState( valueProp );
// Tracks whether the internal point value has not propagated.
const isPointHeld = useRef();
const { current: keepPoint } = useRef( ( value ) => {
// Tracks the internal point value when it’s yet to be propagated.
const refPoint = useRef();
const keepPoint = ( value ) => {
setPoint( value );
isPointHeld.current = true;
} );
const sendPoint = ( value = point ) => {
refPoint.current = value;
};
const sendPoint = ( value = refPoint.current ) => {
onChange?.( value );
isPointHeld.current = false;
refPoint.current = undefined;
};
// Uses the internal point if it is held or else the value from props.
const { x, y } = isPointHeld.current ? point : valueProp;
const { x, y } = refPoint.current !== undefined ? point : valueProp;

const dragAreaRef = useRef();
const [ bounds, setBounds ] = useState( INITIAL_BOUNDS );
Expand Down Expand Up @@ -96,14 +96,10 @@ export default function FocalPointPicker( {
},
onDragEnd: ( event ) => {
onDragEnd?.( event );
sendPoint();
},
} );

// Propagates the value when a drag gesture has ended.
useEffect( () => {
if ( ! isDragging && isPointHeld.current ) sendPoint();
}, [ isDragging ] );

const getValueWithinDragArea = ( { clientX, clientY, shiftKey } ) => {
const { top, left } = dragAreaRef.current.getBoundingClientRect();
let nextX = ( clientX - left ) / bounds.width;
Expand Down

0 comments on commit 832ea2c

Please sign in to comment.