π React + TypeScript Cheat Sheet
npx create-react-app my-app --template typescript
# or with Vite
npm create vite@latest my-app -- --template react-ts
.tsx
: For files that include JSX
.ts
: For files without JSX
Functional Component (FC)
import React from 'react' ;
type Props = {
title : string ;
count ?: number ; // optional prop
} ;
const MyComponent : React . FC < Props > = ( { title, count = 0 } ) => (
< h1 > { title } - { count } </ h1 >
) ;
type Props = {
title : string ;
} ;
function Header ( { title } : Props ) {
return < h1 > { title } </ h1 > ;
}
const [ count , setCount ] = useState < number > ( 0 ) ;
const [ name , setName ] = useState < string | null > ( null ) ;
useEffect ( ( ) => {
console . log ( 'Component mounted' ) ;
} , [ ] ) ;
type Props = {
children : React . ReactNode ;
} ;
const Wrapper = ( { children } : Props ) => < div > { children } </ div > ;
const handleClick = ( e : React . MouseEvent < HTMLButtonElement > ) => {
console . log ( e . currentTarget ) ;
} ;
const handleChange = ( e : React . ChangeEvent < HTMLInputElement > ) => {
setValue ( e . target . value ) ;
} ;
const inputRef = useRef < HTMLInputElement > ( null ) ;
< input ref = { inputRef } /> ;
type Theme = 'light' | 'dark' ;
const ThemeContext = createContext < Theme > ( 'light' ) ;
const useTheme = ( ) => useContext ( ThemeContext ) ;
// Interface
interface User {
name : string ;
age : number ;
}
// Type
type User = {
name : string ;
age : number ;
} ;
type Todo = {
id : number ;
title : string ;
completed : boolean ;
} ;
const [ todos , setTodos ] = useState < Todo [ ] > ( [ ] ) ;
useEffect ( ( ) => {
fetch ( '/api/todos' )
. then ( res => res . json ( ) )
. then ( data => setTodos ( data ) ) ;
} , [ ] ) ;
{ todos . map ( todo => (
< li key = { todo . id } > { todo . title } </ li >
) ) }
π§± Custom Hooks (with Type)
function useToggle ( initial : boolean ) : [ boolean , ( ) => void ] {
const [ state , setState ] = useState ( initial ) ;
const toggle = ( ) => setState ( ! state ) ;
return [ state , toggle ] ;
}
type ButtonProps = React . ButtonHTMLAttributes < HTMLButtonElement > ;
const Button = ( props : ButtonProps ) => < button { ...props } /> ;