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
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

React Hooks – `useState`, `useEf | TypeScript Mastery lesson | BraveProgrammer
  1. Courses
  2. /
  3. TypeScript Mastery

Lesson 29 of 56

·Typescript

React Hooks – `useState`, `useEffect` Types

20 minutes

Course progress52%

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.
Make it stickPractice what you've learned1 quiz · 3 practical tests · Optional activities from TypeScript MasteryBrowse activities
Previous lessonReact Props & State TypingContinue to lesson 30React Context API TypingBack to TypeScript Mastery curriculum