Lesson 8 of 8
Practice & Quiz - TypeScript with React
Reinforce your React + TypeScript skills - typed props, event handlers, hooks, custom hooks, and context - with a practical component exercise and 5 quiz questions.
Practical: Typed useAsync Custom Hook
// A reusable, fully-typed async data fetching hook
import React from "react";
interface AsyncState<T> {
data: T | null;
loading: boolean;
error: string | null;
}
// Generic hook - T inferred from the fetcher return type
function useAsync<T>(
fetcher: () => Promise<T>,
deps: React.DependencyList = [],
): AsyncState<T> & { refetch: () => void } {
const [state, setState] = React.useState<AsyncState<T>>({
data: null, loading: true, error: null,
});
const run = React.useCallback(async () => {
setState(s => ({ ...s, loading: true, error: null }));
try {
const data = await fetcher();
setState({ data, loading: false, error: null });
} catch (err: unknown) {
setState({
data: null,
loading: false,
error: err instanceof Error ? err.message : "Unknown error",
});
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, deps);
React.useEffect(() => { void run(); }, [run]);
return { ...state, refetch: run };
}
// Usage - TypeScript infers Task[] from taskApi.getAll():
function TaskDashboard(): React.ReactElement {
const { data: tasks, loading, error, refetch } = useAsync(
() => taskApi.getAll(),
[],
);
// tasks: Task[] | null - fully typed ✅
if (loading) return <p>Loading…</p>;
if (error) return <p className="error">{error} <button onClick={refetch}>Retry</button></p>;
if (!tasks) return <p>No tasks.</p>;
return (
<ul>
{tasks.map(t => <li key={t.id}>{t.title} - {t.status}</li>)}
</ul>
);
}Module Quiz
Why is using a plain typed function preferred over `React.FC<Props>` for component definitions in modern React?
Tip
Tip
Practice Practice Quiz TypeScript with React in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
TypeScript = JavaScript + static types → fewer bugs, better tooling
Practice Task
Note
Practice Task - (1) Write a working example of Practice Quiz TypeScript with React from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with Practice Quiz TypeScript with React is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready typescript code.
Finished this lesson?