Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

Files page: stop re-rendering for a poll that found nothing (#8157)

ConnorYoh14900704c171
diff --git a/frontend/editor/src/core/components/filesPage/useFolderFileStates.test.tsx b/frontend/editor/src/core/components/filesPage/useFolderFileStates.test.tsx
index 96d2e55958..eba96e781a 100644
--- a/frontend/editor/src/core/components/filesPage/useFolderFileStates.test.tsx
+++ b/frontend/editor/src/core/components/filesPage/useFolderFileStates.test.tsx
@@ -1,6 +1,13 @@
import type { ReactNode } from "react";
import { afterEach, beforeEach, describe, expect, it, test, vi } from "vitest";
-import { act, cleanup, renderHook, waitFor } from "@testing-library/react";
+import { Profiler, type ReactElement } from "react";
+import {
+ act,
+ cleanup,
+ render,
+ renderHook,
+ waitFor,
+} from "@testing-library/react";
import { QueryClientProvider } from "@tanstack/react-query";
import { createAppQueryClient } from "@app/query/queryClient";
import { useFolderFileStates } from "@app/components/filesPage/useFolderFileStates";
@@ -176,3 +183,56 @@ describe("processing file locks", () => {
expect(result.current.processingLockedFor("new.pdf")).toBe(false);
});
});
+
+/**
+ * The files page renders a row per file and a card per folder, so anything this
+ * hook re-renders for is paid many times over. A poll that found nothing new is
+ * the common case and has to cost nothing.
+ */
+test("a poll that changed nothing does not re-render its readers", async () => {
+ vi.useFakeTimers({ shouldAdvanceTime: true });
+ const Wrapper = queryWrapper();
+ let commits = 0;
+
+ function Probe() {
+ const { fileStates } = useFolderFileStates("rec-quiet", true);
+ return <span>{fileStates.size}</span>;
+ }
+
+ const settle = async () => {
+ for (let i = 0; i < 4; i += 1) {
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ }
+ };
+
+ render(
+ (
+ <Wrapper>
+ <Profiler
+ id="files"
+ onRender={() => {
+ commits += 1;
+ }}
+ >
+ <Probe />
+ </Profiler>
+ </Wrapper>
+ ) as ReactElement,
+ );
+ await settle();
+ const reads = listFiles.mock.calls.length;
+ commits = 0;
+
+ // Ten ticks, the same answer every time.
+ for (let i = 0; i < 10; i += 1) {
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(3000);
+ });
+ await settle();
+ }
+
+ expect(listFiles.mock.calls.length).toBeGreaterThan(reads);
+ expect(commits).toBe(0);
+});
diff --git a/frontend/editor/src/core/components/filesPage/useFolderFileStates.ts b/frontend/editor/src/core/components/filesPage/useFolderFileStates.ts
index 3868cb8847..0e3da31405 100644
--- a/frontend/editor/src/core/components/filesPage/useFolderFileStates.ts
+++ b/frontend/editor/src/core/components/filesPage/useFolderFileStates.ts
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { useCallback, useMemo, useRef } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import type { DiskFileState } from "@app/components/filesPage/FileGrid";
import {
@@ -23,11 +23,14 @@ export function useFolderFileStates(
const { listFiles } = useProcessingFolders();
const queryClient = useQueryClient();
const processingFilesKey = qk.processingFolderFiles(processingRecordId ?? "");
+ // Only properties a quiet poll leaves alone: `data` keeps its identity under
+ // structural sharing, `isError` moves on a transition and `errorUpdateCount`
+ // on a failure. Reading `dataUpdatedAt` or `status` here re-rendered every
+ // view on the page every 3s to say nothing had changed.
const {
data: processingFiles,
- dataUpdatedAt: processingFilesUpdatedAt,
- errorUpdatedAt: processingFilesErrorAt,
- status: processingFilesStatus,
+ isError: processingPollFailed,
+ errorUpdateCount,
} = useQuery({
queryKey: processingFilesKey,
queryFn: () => listFiles(processingRecordId!),
@@ -37,43 +40,21 @@ export function useFolderFileStates(
});
const activeProcessingKey = enabled ? (processingRecordId ?? "") : "";
- const [processingPollFailures, setProcessingPollFailures] = useState({
- key: "",
- count: 0,
- });
- const processingPollEvent = useRef({ key: "", updatedAt: 0 });
- useEffect(() => {
- const key = activeProcessingKey;
- if (processingPollEvent.current.key !== key) {
- processingPollEvent.current = { key, updatedAt: 0 };
- setProcessingPollFailures({ key, count: 0 });
- }
- if (!key) return;
-
- const updatedAt =
- processingFilesStatus === "error"
- ? processingFilesErrorAt
- : processingFilesUpdatedAt;
- if (!updatedAt || updatedAt <= processingPollEvent.current.updatedAt)
- return;
-
- processingPollEvent.current.updatedAt = updatedAt;
- setProcessingPollFailures((failures) => ({
- key,
- count:
- processingFilesStatus === "error"
- ? (failures.key === key ? failures.count : 0) + 1
- : 0,
- }));
- }, [
- activeProcessingKey,
- processingFilesErrorAt,
- processingFilesStatus,
- processingFilesUpdatedAt,
- ]);
+ // Failures since the last good poll, held as a baseline rather than counted
+ // into state, so tracking them costs no render of its own.
+ const failuresBefore = useRef({ key: "", errors: 0 });
+ if (failuresBefore.current.key !== activeProcessingKey) {
+ failuresBefore.current = {
+ key: activeProcessingKey,
+ errors: errorUpdateCount,
+ };
+ } else if (!processingPollFailed) {
+ failuresBefore.current.errors = errorUpdateCount;
+ }
const processingStatesUnavailable =
- processingPollFailures.key === activeProcessingKey &&
- processingPollFailures.count >= PROCESSING_FILES_FAILURE_LIMIT;
+ Boolean(activeProcessingKey) &&
+ errorUpdateCount - failuresBefore.current.errors >=
+ PROCESSING_FILES_FAILURE_LIMIT;
const fileStates = useMemo(
() =>