From 3acdaf8a2a3deb3f05d2448afc3244ca8511ed6d Mon Sep 17 00:00:00 2001 From: 0x1eef <0x1eef@protonmail.com> Date: Mon, 4 Dec 2023 01:59:13 -0300 Subject: [PATCH] Optimize memo of Stream.tsx The Stream only has to re-render when 'stream.length' changes, but could be re-rendered by a parent in scenarios where 'stream.length' has not changed. This change optimizes that scenario by only re-rendering the stream when 'stream.length' changes. --- src/js/components/Stream.tsx | 66 ++++++++++++++++++------------------ 1 file changed, 33 insertions(+), 33 deletions(-) diff --git a/src/js/components/Stream.tsx b/src/js/components/Stream.tsx index 211da4c..4fef28c 100644 --- a/src/js/components/Stream.tsx +++ b/src/js/components/Stream.tsx @@ -26,44 +26,44 @@ export function Stream({ const className = classNames("body", "stream"); const style: React.CSSProperties = endOfStream || isPaused ? { overflowY: "auto" } : { overflowY: "hidden" }; - const ul = useRef(); - const ayat = useMemo(() => { - return stream.map((ayah: Quran.Ayah) => { - return ( -
  • - - {(isPaused || endOfStream) && ( - turnOffSound()} - /> - )} - - {t(locale, "surah")} {formatNumber(surah.id, locale)} - {t(locale, "comma")} {t(locale, "ayah")}{" "} - {formatNumber(ayah.id, locale)} - - -

    {ayah.text}

    -
  • - ); - }); + const ref = useRef(); + const ul = useMemo(() => { + return ( +
      + {stream.map((ayah: Quran.Ayah) => { + return ( +
    • + + {(isPaused || endOfStream) && ( + turnOffSound()} + /> + )} + + {t(locale, "surah")} {formatNumber(surah.id, locale)} + {t(locale, "comma")} {t(locale, "ayah")}{" "} + {formatNumber(ayah.id, locale)} + + +

      {ayah.text}

      +
    • + ); + })} +
    + ); }, [stream.length]); useEffect(() => { - const el = ul.current; + const el = ref.current; if (el) { - const top = el.scrollHeight + el.scrollTop; - el.scrollTo({ behavior: "smooth", top }); + const top = 1024 + el.scrollHeight + el.scrollTop; + el.scrollBy({ behavior: "smooth", top }); el.scrollIntoView({ behavior: "smooth" }); } - }, [ul.current, stream.length]); + }, [stream.length]); - return ( -
      - {ayat} -
    - ); + return ul; }