Crash Courses · Masters
TypeScript in React & Next.js
Type React components, props, hooks, and event handlers correctly.
12 min read+175 XP on completionCert: TypeScript Crash Course
Tap any word in the text below to start reading from there.
TypeScript in React & Next.js
Every component, hook, and event handler has proper TypeScript types.
Component Props
interface ButtonProps {
label: string
onClick: () => void
variant?: 'primary' | 'secondary' | 'ghost'
disabled?: boolean
children?: React.ReactNode
}
export function Button({ label, onClick, variant = 'primary', disabled }: ButtonProps) {
return (
<button className={`btn btn-${variant}`} onClick={onClick} disabled={disabled}>
{label}
</button>
)
}useState with Types
const [count, setCount] = useState(0) // inferred: number
const [name, setName] = useState('') // inferred: string
// Generic needed when initial value is null
const [user, setUser] = useState<User | null>(null)
const [courses, setCourses] = useState<Course[]>([])useRef for DOM Elements
const inputRef = useRef<HTMLInputElement>(null)
useEffect(() => {
inputRef.current?.focus()
}, [])
return <input ref={inputRef} type="text" />Event Handlers
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setValue(e.target.value)
}
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault()
}
const handleClick = (e: React.MouseEvent<HTMLButtonElement>) => {
e.stopPropagation()
}Next.js App Router Types
interface PageProps {
params: { id: string }
searchParams: { [key: string]: string | string[] | undefined }
}
export default function CoursePage({ params }: PageProps) {
const course = getCourse(params.id)
if (!course) notFound()
return <CourseView course={course} />
}Reading progress
0% read
In this module
ComponentProps
useState type
useRef type
Event types
0%