From 4a362b7db8aab68e016d02eccfb98e7b12db507f Mon Sep 17 00:00:00 2001 From: 0x1eef <0x1eef@protonmail.com> Date: Fri, 24 May 2024 14:02:02 -0300 Subject: [PATCH] Reduce re-renders of SurahStream (SurahStream/index.tsx) --- src/js/components/SurahStream/Timer.tsx | 26 +++++++++++++++---------- src/js/components/SurahStream/index.tsx | 14 +------------ 2 files changed, 17 insertions(+), 23 deletions(-) diff --git a/src/js/components/SurahStream/Timer.tsx b/src/js/components/SurahStream/Timer.tsx index 6636b38..5479d69 100644 --- a/src/js/components/SurahStream/Timer.tsx +++ b/src/js/components/SurahStream/Timer.tsx @@ -1,4 +1,4 @@ -import React, { useEffect } from "react"; +import React, { useEffect, useState } from "react"; import type { Surah, Ayah, TLocale } from "Quran"; import { formatNumber } from "~/lib/t"; @@ -9,9 +9,7 @@ type Props = { surah: Surah; ayah: Maybe; isPaused: boolean; - isStalled: boolean; - ms: number | null; - setMs: (n: number) => void; + audioStatus: Maybe; onComplete: (surah: Surah, ayah: Ayah) => void; }; @@ -20,17 +18,25 @@ export function Timer({ surah, ayah, isPaused, - isStalled, - ms, - setMs, + audioStatus, onComplete, }: Props) { + const [ms, setMs] = useState(null); + const isStalled = audioStatus === "wait"; + useEffect(() => { - if (ayah) { - setMs(ayah.ms); - } + if (!ayah) + return + setMs(ayah.ms); }, [ayah?.id]); + useEffect(() => { + if (!ayah) + return + if (audioStatus === "play") + setMs(ayah.ms) + }, [audioStatus]); + useEffect(() => { if (!ayah || typeof ms !== "number") { return; diff --git a/src/js/components/SurahStream/index.tsx b/src/js/components/SurahStream/index.tsx index d6da8f8..1e9f292 100644 --- a/src/js/components/SurahStream/index.tsx +++ b/src/js/components/SurahStream/index.tsx @@ -23,7 +23,6 @@ export function SurahStream({ surah, locale, t }: Props) { const [audioStatus, setAudioStatus] = useState>(null); const [endOfStream, setEndOfStream] = useState(false); const [theme, setTheme] = useTheme(); - const [ms, setMs] = useState(null); const articleRef = useRef(null); const audio = useMemo(() => new Audio(), []); const readyToRender = stream.length > 0; @@ -36,12 +35,6 @@ export function SurahStream({ surah, locale, t }: Props) { } }, [articleRef.current, theme]); - useEffect(() => { - if (ayah) { - setMs(ayah.ms); - } - }, [ayah]); - useEffect(() => { if (!endOfStream) { setStream([surah.ayat[0]]); @@ -84,9 +77,6 @@ export function SurahStream({ surah, locale, t }: Props) { ayah={ayah} hidden={endOfStream} onStatusChange={status => { - if (status === "play") { - setMs(ayah.ms); - } setAudioStatus(status); }} /> @@ -101,9 +91,7 @@ export function SurahStream({ surah, locale, t }: Props) { surah={surah} ayah={ayah} isPaused={isPaused} - isStalled={audioStatus === "wait"} - ms={ms} - setMs={setMs} + audioStatus={audioStatus} onComplete={(surah, ayah) => { const layah = surah.ayat[surah.ayat.length - 1]; if (!layah || !ayah) {