NUS Hackers Wiki
NUS Hackers Wiki
  • NUS Hackers Wiki
  • Hackerschool
    • Virtual Machines and Linux
    • Beginners' Guide to the Terminal
      • Introduction to the Terminal
      • Modern Shell Tools
      • Shell Scripting
      • Real World Scripting
      • Resources
    • Self-Hosting: Three Easy Pieces
      • 1. Setting up your server
      • 2. Running Services
      • 3. Monitoring your server
    • Vim
    • Introduction to Zig
      • Language Basics
      • Error Handling
      • Memory Management
      • Working with C
      • Exploring comptime
    • CI/CD with Github Actions
      • Background
      • Basics of Github Actions
        • Target workflow
        • Running unit tests
        • Linting code
        • Deploying to Github Pages
      • Advanced use cases
        • Pollers
        • Github script
        • Executing third-party scripts
        • Reusable workflows
      • Cookbook
    • Lightning Git
      • Git Concepts
      • Getting Started with Git
      • Making your first commit
      • Branching
      • Merge Conflicts
      • Integrating remote repositories
      • Collaborative Workflows
      • Commit Manipulation and Reflog
      • Interactive rebasing
      • filter-repo
  • Orbital
    • JavaScript
      • Browser Developer Tools
      • Getting Started
      • Datatypes
      • Operators and Operations
      • Loops and Conditions
      • Functions
      • Strings
      • Arrays
      • HTML
        • Getting Started
        • Tag Attributes
        • HTML Forms
        • Browser Inspector
      • CSS
        • Selectors
        • Colors in CSS
        • Measurements in CSS
        • The Box Model
        • Adding Styles - Part 1
        • Adding Styles - Part 2
      • Working with the DOM
        • Querying the DOM - Selectors
        • Querying the DOM - Element Attributes
        • Querying the DOM - Element Styles
        • Events with JS and HTML
        • Exercise: Click Counter
        • Editing the DOM
        • Fetch Requests
        • Exercise: The NUSMods API
    • React
      • Setup
      • State
    • React Native
      • Setup
      • Intro to JSX
      • Basic Syntax
      • Handling UI
      • Props
      • State Management
    • Git
      • Setup
      • Command Glossary
      • Fundamental Concepts
        • Getting Started
        • Integrating Remote Repositories
        • Branching
        • Merge Conflicts
      • Collaborative Workflows
        • Fork and PR Workflow
        • Branch and PR Workflow
      • Advanced Concepts
        • Ignoring Files
        • Commit Message Conventions
        • Github Collaborators
        • CI/CD with Github Actions
        • Advanced Git Commands
      • FAQ
    • Telegram Bot
      • Creating a TeleBot
      • API Calls
      • Telebot Basics
      • Integrating API's
    • Relational Database
      • Database Overview
      • Database Design
      • Entity Relationship Diagram
      • SQL Basics & PostgreSQL
    • TypeScript
      • Types and Interfaces
      • Utility Types
      • Typing Component Props, Events, and Hooks
      • Why You Should Avoid Using any (and What to Do Instead)
      • TypeScript Tricks You’ll Use All the Time in React
Powered by GitBook
On this page
  • Typing Component Props
  • Typing useState
  • Step 1: Create the state type
  • Step 2: Type the useState hook
  • Step 3: Using setTodos
  • Typing Events
  • Typing Custom Hooks
Edit on GitHub
Export as PDF
  1. Orbital
  2. TypeScript

Typing Component Props, Events, and Hooks

TypeScript really shines in React when working with component props, events, and hooks like useState or useEffect. Here’s how to type them properly so you get type safety and helpful autocompletions.

Typing Component Props

interface Todo {
  title: string;
  done: boolean;
}

interface TodoItemProps {
  todo: Todo;
  onToggle: (title: string) => void;
}

const TodoItem: React.FC<TodoItemProps> = ({ todo, onToggle }) => (
  <div>
    <input
      type="checkbox"
      checked={todo.done}
      onChange={() => onToggle(todo.title)}
    />
    {todo.title}
  </div>
);

💡 Tip: Try it in your IDE!

With typed props, you’ll get autocompletion and instant feedback — making mistakes harder and coding faster.

Typing useState

Step 1: Create the state type

interface Todo {
  title: string;
  done: boolean;
}

Step 2: Type the useState hook

// empty initial state
const [todos, setTodos] = useState<Todo[]>([]);
const INITIAL_TODO: Todo[] = [
  {
    title: "first task",
    done: false,
  },
  {
    title: "second task",
    done: true,
  },
  {
    title: "third task",
    done: true,
  },
];

const [todos, setTodos] = useState<Todo[]>(INITIAL_TODO);

Now todos is typed as an array of Todo objects, and setTodos will only accept that type.

Step 3: Using setTodos

Here are three valid and clean ways to use setTodos:

// 1. Basic usage — straightforward and readable
setTodos([{ title: "new todo", done: false }]);

// 2. Callback form — preferred if referencing previous state or writing multiple lines
setTodos((prevTodos) => {
  return [...prevTodos, { title: "new todo", done: false }];
});

// 3. One-liner callback — clean if short
setTodos((prev) => [...prev, { title: "new todo", done: false }]);

React batches updates — using the callback ensures you’re working with the most recent state, especially inside useEffect or async operations.

Typing Events

React’s synthetic events are strongly typed too. Here’s an example with an input change handler:

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

Typing Custom Hooks

If you create your own hooks, type the input and output clearly:

function useTodoList(): [Todo[], (todo: Todo) => void] {
  const [todos, setTodos] = useState<Todo[]>([]);

  const addTodo = (todo: Todo) => setTodos((prev) => [...prev, todo]);

  return [todos, addTodo];
}
const [todos, addTodo] = useTodoList();
addTodo({ title: "Learn TS", done: false });
PreviousUtility TypesNextWhy You Should Avoid Using any (and What to Do Instead)

Last updated 3 days ago

Why use the callback form?

🧠