Skip to content

Commit

Permalink
use useTransition for tab container
Browse files Browse the repository at this point in the history
  • Loading branch information
n3dst4 committed Jun 6, 2024
1 parent d7eb349 commit 809c229
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
9 changes: 8 additions & 1 deletion src/components/TabContainer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import React, {
useContext,
useMemo,
useState,
useTransition,
} from "react";

import { ThemeContext } from "../themes/ThemeContext";
Expand All @@ -28,12 +29,17 @@ export const TabContainer: React.FC<TabContainerProps> = ({
defaultTab,
}) => {
const [selected, setSelected] = useState(defaultTab);
const [optimistic, setOptimistic] = useState(defaultTab);
const [pending, startTransition] = useTransition();
const activeTabDef = useMemo(
() => tabs.find((t) => t.id === selected),
[selected, tabs],
);
const onChange = useCallback((e: ChangeEvent<HTMLInputElement>) => {
setSelected(e.currentTarget.value);
setOptimistic(e.currentTarget.value);
startTransition(() => {
setSelected(e.currentTarget.value);
});
}, []);

const theme = useContext(ThemeContext);
Expand Down Expand Up @@ -89,6 +95,7 @@ export const TabContainer: React.FC<TabContainerProps> = ({
display: "flex",
flexDirection: "column",
justifyContent: "center",
opacity: pending && id === optimistic ? 0.5 : 1,
}}
>
{typeof label === "string" ? (
Expand Down
21 changes: 21 additions & 0 deletions src/components/settings/Slow.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import React, { memo } from "react";

function SlowPost({ index }: { index: number }) {
const startTime = performance.now();
while (performance.now() - startTime < 1) {
// Do nothing for 1 ms per item to emulate extremely slow code
}

return <li className="item">Post #{index + 1}</li>;
}

export const Slow = memo(function PostsTab() {
// Log once. The actual slowdown is inside SlowPost.
console.log("[ARTIFICIALLY SLOW] Rendering 500 <SlowPost />");

const items = [];
for (let i = 0; i < 300; i++) {
items.push(<SlowPost key={i} index={i} />);
}
return <ul className="items">{items}</ul>;
});

0 comments on commit 809c229

Please sign in to comment.