Search code examples
javascriptreactjscanvasreact-hooksscroll

Canvas is clearing on scroll


function Component2 ():JSX.Element {
   return (<canvas width="300" height="300></canvas>);
}
export default function Component1(): JSX.Element {
           const scrollToEndRef = useRef(null);
           const [hideScrollEnd, setHideScrollEnd] = useState(false);
      useEffect(() => {
           window.addEventListener('scroll', (e) => {
            if (
                window.innerHeight + window.scrollY >
                document.body.clientHeight - 100
            ) {
                setHideScrollEnd(true);
            } else {
                setHideScrollEnd(false);
            }
            e.stopPropagation();
        }, false);
       }, []);
       return (
               <>
               <Component2/>
               {!hideScrollEnd && (
                    <Button ref={scrollToEndRef}>
                         Scroll to the end
                    </Button>)}
                </>
        );
}

If I draw something in canvas. On scroll reaching bottom, "scroll to end" button is hiding as expected. But, canvas is also getting cleared on hiding the button. Anyway to persist the canvas drawing.


Solution

  • You change hideScrollEnd, which rerenders your component, including the canvas, that's why it gets cleared, it's a new canvas.

    There are 2 possible solutions at least:

    1. Move the scroll/hide logic in to the button component itself (means you may need to create your own CustomButton component or something like that)

    2. Memoize the Component2

    const memoizedComponent2 = useMemo(() => , [...dependencies]);

    where listOfDepencenies are all the variables which on change should cause the Component2 to rerender.

    in your JSX you than use {memoizedComponent2} instead of <Component2/>