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.
This commit is contained in:
0x1eef 2023-12-04 01:59:13 -03:00
parent 1a7af1be2a
commit 46850a8cfb

View file

@ -26,9 +26,11 @@ export function Stream({
const className = classNames("body", "stream"); const className = classNames("body", "stream");
const style: React.CSSProperties = const style: React.CSSProperties =
endOfStream || isPaused ? { overflowY: "auto" } : { overflowY: "hidden" }; endOfStream || isPaused ? { overflowY: "auto" } : { overflowY: "hidden" };
const ul = useRef<HTMLUListElement>(); const ref = useRef<HTMLUListElement>();
const ayat = useMemo<JSX.Element[]>(() => { const ul = useMemo<JSX.Element>(() => {
return stream.map((ayah: Quran.Ayah) => { return (
<ul lang={locale} className={className} style={style} ref={ref}>
{stream.map((ayah: Quran.Ayah) => {
return ( return (
<li key={ayah.id} className="ayah fade"> <li key={ayah.id} className="ayah fade">
<span className="title"> <span className="title">
@ -49,21 +51,19 @@ export function Stream({
<p>{ayah.text}</p> <p>{ayah.text}</p>
</li> </li>
); );
}); })}
</ul>
);
}, [stream.length]); }, [stream.length]);
useEffect(() => { useEffect(() => {
const el = ul.current; const el = ref.current;
if (el) { if (el) {
const top = el.scrollHeight + el.scrollTop; const top = 1024 + el.scrollHeight + el.scrollTop;
el.scrollTo({ behavior: "smooth", top }); el.scrollBy({ behavior: "smooth", top });
el.scrollIntoView({ behavior: "smooth" }); el.scrollIntoView({ behavior: "smooth" });
} }
}, [ul.current, stream.length]); }, [stream.length]);
return ( return ul;
<ul lang={locale} className={className} style={style} ref={ul}>
{ayat}
</ul>
);
} }