Skip to content

Commit

Permalink
Use event callback to prevent re-renders
Browse files Browse the repository at this point in the history
  • Loading branch information
Mitch-At-Work committed Oct 21, 2024
1 parent e70f13c commit e65f158
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ export type CarouselContextValues = {
};

// @public (undocumented)
export type CarouselIndexChangeData = EventData<'click' | 'focus', React_2.FocusEvent | React_2.MouseEvent<HTMLButtonElement | HTMLAnchorElement>> & {
export type CarouselIndexChangeData = EventData<'click' | 'focus' | 'drag', TouchEvent | MouseEvent | React_2.FocusEvent | React_2.MouseEvent<HTMLButtonElement | HTMLAnchorElement>> & {
index: number;
};

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { EventHandler, useControllableState } from '@fluentui/react-utilities';
import { EventHandler, useControllableState, useEventCallback } from '@fluentui/react-utilities';
import EmblaCarousel, { EmblaPluginType, type EmblaCarouselType, type EmblaOptionsType } from 'embla-carousel';
import * as React from 'react';

Expand Down Expand Up @@ -51,6 +51,9 @@ export function useEmblaCarousel(
initialState: 0,
});

const onDragEvent = useEventCallback((event: TouchEvent | MouseEvent, index: number) => {
onDragIndexChange?.(event, { event, type: 'drag', index });
});
const dragEventRef = React.useRef<MouseEvent | TouchEvent | undefined>(undefined);
const watchDragEvent = React.useCallback(
(_emblaApi: EmblaCarouselType, event: MouseEvent | TouchEvent) => {
Expand Down Expand Up @@ -141,7 +144,7 @@ export function useEmblaCarousel(
const actualIndex = emblaApi.current?.internalEngine().slideRegistry[newIndex][0] ?? 0;

if (dragEventRef.current) {
onDragIndexChange?.(dragEventRef.current, { event: dragEventRef.current, type: 'drag', index: newIndex });
onDragEvent(dragEventRef.current, newIndex);
dragEventRef.current = undefined;
}
// We set the active or first index of group on-screen as the selected tabster index
Expand Down Expand Up @@ -208,7 +211,7 @@ export function useEmblaCarousel(
}
},
};
}, [getPlugins, setActiveIndex]);
}, [getPlugins, onDragEvent, setActiveIndex]);

const carouselApi = React.useMemo(
() => ({
Expand Down

0 comments on commit e65f158

Please sign in to comment.