Lesson 29 of 56 · Typescript
React Hooks – `useState`, `useEffect` Types
Duration: 20 minutes
useState
const [items, setItems] = useState<string[]>([]);
When initializing with a function, provide a generic:
const [count, setCount] = useState(() => computeInitial()); // inferred
useEffect Dependency Array
useEffect(() => {
// do something when `id` changes
}, [id]);
If you need to type the cleanup function:
useEffect(() => {
const timer = setInterval(...);
return () => clearInterval(timer);
}, []);
Custom Hook with Generics
function useAsync<T>(promiseFn: () => Promise<T>) {
const [data, setData] = useState<T | null>(null);
const [error, setError] = useState<Error | null>(null);
useEffect(() => {
promiseFn()
.then(setData)
.catch(setError);
}, [promiseFn]);
return { data, error };
}