From 133b4e3d99028782983973677f7b2d6676c9781b Mon Sep 17 00:00:00 2001 From: J Scott Smith Date: Mon, 20 Nov 2023 15:47:05 -0800 Subject: [PATCH] fix: create controller only once --- .../ParallaxProvider/ParallaxProvider.tsx | 13 +++++++------ src/components/ParallaxProvider/index.test.tsx | 16 ++++++++++++++-- 2 files changed, 21 insertions(+), 8 deletions(-) diff --git a/src/components/ParallaxProvider/ParallaxProvider.tsx b/src/components/ParallaxProvider/ParallaxProvider.tsx index fe604189..20cfbad1 100644 --- a/src/components/ParallaxProvider/ParallaxProvider.tsx +++ b/src/components/ParallaxProvider/ParallaxProvider.tsx @@ -1,20 +1,22 @@ import React, { PropsWithChildren, useEffect, useRef } from 'react'; import { ParallaxContext } from '../../context/ParallaxContext'; -import { ScrollAxis } from 'parallax-controller'; +import { ParallaxController, ScrollAxis } from 'parallax-controller'; import { ParallaxProviderProps } from './types'; import { createController } from './helpers'; export function ParallaxProvider( props: PropsWithChildren ) { - const controller = useRef( - createController({ + const controller = useRef(null); + + if (!controller.current) { + controller.current = createController({ scrollAxis: props.scrollAxis || ScrollAxis.vertical, scrollContainer: props.scrollContainer, disabled: props.isDisabled, - }) - ); + }); + } // update scroll container useEffect(() => { @@ -37,7 +39,6 @@ export function ParallaxProvider( useEffect(() => { return () => { controller?.current && controller?.current.destroy(); - controller.current = null; }; }, []); diff --git a/src/components/ParallaxProvider/index.test.tsx b/src/components/ParallaxProvider/index.test.tsx index 8fa04b66..2f156fb9 100644 --- a/src/components/ParallaxProvider/index.test.tsx +++ b/src/components/ParallaxProvider/index.test.tsx @@ -7,6 +7,7 @@ import { ParallaxController } from 'parallax-controller'; import { render } from '@testing-library/react'; import { ParallaxProvider } from '.'; import { useParallaxController } from '../../hooks/useParallaxController'; +import * as helpers from './helpers'; describe('A ', () => { it('to render children', () => { @@ -48,6 +49,15 @@ describe('A ', () => { expect(parallaxController).toBeInstanceOf(ParallaxController); }); + it('calls to createController only once', () => { + jest.spyOn(helpers, 'createController'); + const { rerender } = render(); + rerender(); + rerender(); + rerender(); + expect(helpers.createController).toHaveBeenCalledTimes(1); + }); + it('to disable parallax elements and re-enable', () => { let parallaxController: ParallaxController | null = null; @@ -100,8 +110,10 @@ describe('A ', () => { ); screen.unmount(); - // @ts-expect-error - expect(parallaxController?.destroy).toBeCalled(); + + expect( + (parallaxController as unknown as ParallaxController)?.destroy + ).toBeCalled(); }); it('to update the scroll container when receiving a new container el', () => {