Reduce re-renders of SurahStream (SurahStream/index.tsx)

This commit is contained in:
0x1eef 2024-05-24 14:02:02 -03:00
parent 91216c6005
commit 4a362b7db8
2 changed files with 17 additions and 23 deletions

View file

@ -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<Ayah>;
isPaused: boolean;
isStalled: boolean;
ms: number | null;
setMs: (n: number) => void;
audioStatus: Maybe<string>;
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<number | null>(null);
const isStalled = audioStatus === "wait";
useEffect(() => {
if (ayah) {
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;

View file

@ -23,7 +23,6 @@ export function SurahStream({ surah, locale, t }: Props) {
const [audioStatus, setAudioStatus] = useState<Maybe<TAudioStatus>>(null);
const [endOfStream, setEndOfStream] = useState<boolean>(false);
const [theme, setTheme] = useTheme();
const [ms, setMs] = useState<number | null>(null);
const articleRef = useRef<HTMLElement>(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) {