Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons

© 2026 BraveProgrammer. All rights reserved.

  1. Courses
  2. /
  3. TypeScript Mastery

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 };
}

Info

TypeScript can infer the generic T from the return type of promiseFn.

Previous: React Props & State TypingNext: React Context API Typing