Skip to content

Instantly share code, notes, and snippets.

@AyanUpadhaya
Created May 10, 2025 16:48
Show Gist options
  • Save AyanUpadhaya/60cdb8acbad66968b7a975fceea64e6d to your computer and use it in GitHub Desktop.
Save AyanUpadhaya/60cdb8acbad66968b7a975fceea64e6d to your computer and use it in GitHub Desktop.

πŸ“˜ React + TypeScript Cheat Sheet

πŸ”§ Project Setup

npx create-react-app my-app --template typescript
# or with Vite
npm create vite@latest my-app -- --template react-ts

πŸ“ File Extensions

  • .tsx: For files that include JSX
  • .ts: For files without JSX

🧱 Component Types

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>
);

Without React.FC

type Props = {
  title: string;
};

function Header({ title }: Props) {
  return <h1>{title}</h1>;
}

πŸͺ„ useState Hook

const [count, setCount] = useState<number>(0);
const [name, setName] = useState<string | null>(null);

πŸŒ€ useEffect Hook

useEffect(() => {
  console.log('Component mounted');
}, []);

πŸ“€ Props and Children

type Props = {
  children: React.ReactNode;
};

const Wrapper = ({ children }: Props) => <div>{children}</div>;

πŸ§ͺ Event Handling

const handleClick = (e: React.MouseEvent<HTMLButtonElement>) => {
  console.log(e.currentTarget);
};

⌨️ Form Inputs

const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
  setValue(e.target.value);
};

⛓️ useRef

const inputRef = useRef<HTMLInputElement>(null);

<input ref={inputRef} />;

πŸ“š useContext

type Theme = 'light' | 'dark';

const ThemeContext = createContext<Theme>('light');

const useTheme = () => useContext(ThemeContext);

🧩 Type vs Interface

// Interface
interface User {
  name: string;
  age: number;
}

// Type
type User = {
  name: string;
  age: number;
};

πŸ“¦ Fetching Data

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));
}, []);

πŸ” Lists and Keys

{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];
}

πŸ§ͺ Testing Types

type ButtonProps = React.ButtonHTMLAttributes<HTMLButtonElement>;

const Button = (props: ButtonProps) => <button {...props} />;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment