Skip to content

Commit bfac6b9

Browse files
author
Simone Gentili
committed
feat: complete useTransition() example
1 parent 56a4548 commit bfac6b9

1 file changed

Lines changed: 53 additions & 8 deletions

File tree

react/useTransition/src/App.tsx

Lines changed: 53 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,65 @@
1-
import { useState } from "react";
1+
import { useState, useTransition } from "react";
22

3-
function App() {
3+
function Container() {
44
const [page, setPage] = useState("/");
5+
const [isPending, startTransition] = useTransition();
6+
7+
function navigate(page: string) {
8+
startTransition(() => {
9+
setPage(page);
10+
});
11+
}
12+
13+
const renderMenu = () => {
14+
return (
15+
<div className="menu">
16+
<button onClick={() => navigate("/")}>home</button>
17+
<button onClick={() => navigate("/blog")}>blog</button>
18+
</div>
19+
);
20+
};
21+
22+
const renderLoading = () => {
23+
return (
24+
<>
25+
{renderMenu()}
26+
<div className="loading">loading ...</div>
27+
</>
28+
);
29+
};
30+
31+
const renderPage = (page: string) => {
32+
if (page == "/") return <HomePage />;
33+
if (page == "/blog") return <BlogPage />;
34+
};
35+
36+
if (isPending) return renderLoading();
537

638
return (
739
<>
8-
<h1>useTransaction()</h1>
9-
10-
<button onClick={() => setPage("/")}>home</button>
11-
<button onClick={() => setPage("/blog")}>blog</button>
40+
{renderMenu()}
41+
{renderPage(page)}
42+
</>
43+
);
44+
}
1245

13-
{page === "/" && <HomePage />}
14-
{page === "/blog" && <BlogPage />}
46+
function App() {
47+
return (
48+
<>
49+
<h1>useTransaction()</h1>
50+
<Container />
1551
</>
1652
);
1753
}
1854

55+
function delay(sec: number) {
56+
let startTime = performance.now();
57+
while (performance.now() - startTime < sec * 1000) {}
58+
}
59+
1960
function HomePage() {
61+
delay(0.6);
62+
2063
return (
2164
<>
2265
<h2>Homepage</h2>
@@ -25,6 +68,8 @@ function HomePage() {
2568
}
2669

2770
function BlogPage() {
71+
delay(0.5);
72+
2873
return (
2974
<>
3075
<h2>Blog!</h2>

0 commit comments

Comments
 (0)