'use client';
import { ReactNode, createContext, useEffect, useMemo, useState } from 'react';
export const LocoScrollContext = createContext({
scroll: null
});
type SmoothScrollProviderProps = {
children: ReactNode;
options?: any;
};
export const LocoScrollProvider = ({
children,
options
}: SmoothScrollProviderProps): JSX.Element => {
const [scroll, setScroll] = useState<any>(null);
useEffect(() => {
if (!scroll) {
(async () => {
try {
const LocomotiveScroll = (await import('locomotive-scroll')).default;
const scrollInstance = new LocomotiveScroll({
el: document.querySelector('[data-scroll-container]') as HTMLElement,
...options
});
setScroll(scrollInstance);
} catch (error) {
throw new Error(`[SmoothScrollProvider]: ${error}`);
}
})();
}
return () => {
if (scroll !== null) {
scroll.destroy();
}
};
}, [scroll]);
return (
<LocoScrollContext.Provider value={useMemo(() => ({ scroll }), [scroll])}>
{children}
</LocoScrollContext.Provider>
);
};
LocoScrollContext.displayName = 'LocoScrollContext';
LocoScrollProvider.displayName = 'LocoScrollProvider';