JSTAcademy
0 XP
Dashboard
Crash Courses
TypeScript in React & Next.js
12 min
Masters+175 XP
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} />
}
0%