ReactAdvanced
Data Fetching
Client-side fetch pattern, race condition, caching ও TanStack Query — বাংলায়।
9টি অংশবাংলা ভাষায়
useEffect + fetch
Basic fetchjsx
jsx
function Posts() {
const [posts, setPosts] = useState([]);
const [status, setStatus] = useState("loading"); // loading | error | ok
useEffect(() => {
let cancelled = false;
fetch("/api/posts")
.then((r) => r.json())
.then((data) => {
if (!cancelled) {
setPosts(data);
setStatus("ok");
}
})
.catch(() => {
if (!cancelled) setStatus("error");
});
return () => {
cancelled = true;
};
}, []);
if (status === "loading") return <p>Loading…</p>;
if (status === "error") return <p>ভুল হয়েছে</p>;
return posts.map((p) => <Post key={p.id} post={p} />);
}সাধারণ সমস্যা
- একই URL বারবার fetch — cache দরকার
- Loading/error UI রাখা নিজেকে করতে হয়
- একাধিক component-এ একই ডেটা — duplication
- Update-এর পরে cache invalidation জটিল
TanStack Query
useQueryjsx
jsx
import { useQuery } from "@tanstack/react-query";
function Posts() {
const { data, isLoading, isError } = useQuery({
queryKey: ["posts"],
queryFn: () => fetch("/api/posts").then((r) => r.json()),
});
if (isLoading) return <p>Loading…</p>;
if (isError) return <p>ভুল হয়েছে</p>;
return data.map((p) => <Post key={p.id} post={p} />);
}
// Cache invalidation
const queryClient = useQueryClient();
queryClient.invalidateQueries({ queryKey: ["posts"] });React 19 — use()
use(promise)jsx
jsx
import { use } from "react";
function Posts({ postsPromise }) {
// promise resolved না হওয়া পর্যন্ত — Suspense fallback
const posts = use(postsPromise);
return posts.map((p) => <Post key={p.id} post={p} />);
}
// parent-এ
<Suspense fallback={<p>Loading…</p>}>
<Posts postsPromise={fetchPosts()} />
</Suspense>কখন কী ব্যবহার
সহজ একবারের fetch → custom hook। জটিল caching/revalidation → TanStack Query। Server-rendered (Next.js) → একই query library বা use() + Suspense।
শেষ প্যারায় নিজে practice করুন — কোড কপি করে নিজের এডিটরে চালিয়ে দেখুন।