Logo
READLEARNKNOWCONNECT
Back to Lessons

    Page

  • - Why Use TypeScript with React?
  • - Setting Up React with TypeScript
  • - Typing Props in Functional Components
  • - Typing useState and useRef
  • - Typing API Data
  • - Mini Project Step

28. Next Steps: Exploring TypeScript with React

Level: AdvancedDuration: 18m

Why Use TypeScript with React?

TypeScript helps catch bugs earlier by enforcing types during development. In React, it improves component reliability, reduces runtime errors, and makes your code easier to understand and maintain.

Setting Up React with TypeScript

bash
npm create vite@latest my-app --template react-ts

We use Vite because it’s fast, modern, and supports TypeScript out of the box.

Typing Props in Functional Components

tsx
type ButtonProps = {
  label: string;
  disabled?: boolean;
};

export default function Button({ label, disabled = false }: ButtonProps) {
  return <button disabled={disabled}>{label}</button>;
}

Optional props are marked with a question mark (?). TypeScript enforces that components receive the correct prop types.

Typing useState and useRef

tsx
const [count, setCount] = useState<number>(0);
const inputRef = useRef<HTMLInputElement>(null);

Typing hooks ensures consistency and prevents passing invalid data into your state or refs.

Typing API Data

tsx
interface Post {
  id: number;
  title: string;
  body: string;
}

axios.get<Post[]>("/api/posts").then(response => {
  console.log(response.data);
});

Typing your data responses avoids undefined errors and improves code readability.

ConceptExampleBenefit
Props typingtype Props {}Prevents wrong props
State typinguseState<number>Ensures valid state
API typingaxios.get<Post[]>Safe API responses

Mini Project Step

Convert your existing React Todo component to TypeScript by typing props, state, and functions. Add an interface for todo items and enforce stricter code quality.