Skip to content

Commit

Permalink
feat: move버튼 throttle 적용
Browse files Browse the repository at this point in the history
  • Loading branch information
dladncks1217 committed Jul 8, 2024
1 parent ac0ed64 commit 8e621d8
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
5 changes: 3 additions & 2 deletions src/components/Carousel/Move.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { ComponentPropsWithoutRef, MouseEvent, useContext } from 'react';
import { CarouselContext } from './Carousel';
import useThrottleCallback from '@/hooks/useThrottleCallback';

export interface MoveProps extends ComponentPropsWithoutRef<'button'> {
direction: 'prev' | 'next';
Expand All @@ -13,11 +14,11 @@ const Move = ({ direction = 'next', addFunc, children, ...attributes }: MoveProp

const { handleMovePrev, handleMoveNext } = context;

const handleMove = (e: MouseEvent<HTMLButtonElement>) => {
const handleMove = useThrottleCallback((e: MouseEvent<HTMLButtonElement>) => {
if (addFunc) addFunc();
if (direction === 'prev') return handleMovePrev(e);
return handleMoveNext(e);
};
}, 500);

return (
<button onClick={handleMove} {...attributes}>
Expand Down
26 changes: 26 additions & 0 deletions src/hooks/useThrottleCallback.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { useRef } from 'react';

function useThrottleCallback<Parameter extends any[]>(callback: (...rest: Parameter) => void, delay: number) {
const timerRef = useRef<NodeJS.Timeout>();
const restRef = useRef<Parameter>();

const timeoutCallback = () => {
restRef.current && callback(...restRef.current);

if (timerRef.current) {
timerRef.current = undefined;
}
};

return (...rest: Parameter): void => {
restRef.current = rest;

if (timerRef.current) return;

callback(...rest);
clearTimeout(timerRef.current);
timerRef.current = setTimeout(timeoutCallback, delay);
};
}

export default useThrottleCallback;

0 comments on commit 8e621d8

Please sign in to comment.