diff --git a/lib/DateTimePicker.tsx b/lib/DateTimePicker.tsx index b5c34d8..49df9d4 100644 --- a/lib/DateTimePicker.tsx +++ b/lib/DateTimePicker.tsx @@ -52,6 +52,12 @@ export const DateTimePicker: FC = (defaultProps) => { const mergedOptions = useMemo(() => mergeHooks(options, props), [options, props]); const nodeRef = useRef(null); const flatpickrRef = useRef(undefined); + const mergedOptionsRef = useRef(mergedOptions); + mergedOptionsRef.current = mergedOptions; + const onCreateRef = useRef(onCreate); + onCreateRef.current = onCreate; + const onDestroyRef = useRef(onDestroy); + onDestroyRef.current = onDestroy; useImperativeHandle( defaultProps.ref, @@ -67,20 +73,21 @@ export const DateTimePicker: FC = (defaultProps) => { useEffect(() => { const createFlatpickrInstance = () => { - mergedOptions.onClose = - mergedOptions.onClose || + const opts = mergedOptionsRef.current; + opts.onClose = + opts.onClose || (() => { if (nodeRef.current?.blur) nodeRef.current.blur(); }); // @ts-expect-error for some reason the default import isnt working correctly - flatpickrRef.current = (flatpickr?.default || flatpickr)(nodeRef.current as HTMLElement, mergedOptions); + flatpickrRef.current = (flatpickr?.default || flatpickr)(nodeRef.current as HTMLElement, opts); - onCreate?.(flatpickrRef.current); + onCreateRef.current?.(flatpickrRef.current); }; const destroyFlatpickrInstance = () => { - onDestroy?.(flatpickrRef.current); + onDestroyRef.current?.(flatpickrRef.current); if (flatpickrRef.current) { flatpickrRef.current.destroy(); } @@ -92,7 +99,7 @@ export const DateTimePicker: FC = (defaultProps) => { return () => { destroyFlatpickrInstance(); }; - }, [mergedOptions, onCreate, onDestroy]); + }, []); useEffect(() => { if (flatpickrRef.current) { diff --git a/test/index.spec.tsx b/test/index.spec.tsx index 912e697..65d7191 100644 --- a/test/index.spec.tsx +++ b/test/index.spec.tsx @@ -121,4 +121,16 @@ describe('react-flatpickr', () => { expect(spy).toHaveBeenCalled(); }); }); + + describe('when options are passed inline without memoization', () => { + it('does not recreate the flatpickr instance when re-rendered with inline options', () => { + const spy = jest.fn(); + const {unmount, rerender} = render(); + + rerender(); + + expect(spy).toHaveBeenCalledTimes(1); + unmount(); + }); + }); });