Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Impara Typing Higher-Order Functions and Callback Props | Advanced React Patterns with TypeScript
Quizzes & Challenges
Quizzes
Challenges
/
TypeScript Essentials for React

bookTyping Higher-Order Functions and Callback Props

When you build React components, you often need to pass functions as props so that child components can notify parents of events, changes, or actions. These are called callback props. Typing callback props precisely in TypeScript helps ensure your components interact correctly and safely, catching possible errors at compile time.

Suppose you have a button component that notifies its parent when it is clicked. You can define the callback prop with a function type that matches the expected signature. For a simple click with no arguments:

type ButtonProps = {
  onClick: () => void;
};

function Button({ onClick }: ButtonProps) {
  return <button onClick={onClick}>Click me</button>;
}

If the callback should receive data, such as an item ID, you can specify the type of the argument:

type ItemButtonProps = {
  onSelect: (id: string) => void;
  id: string;
};

function ItemButton({ onSelect, id }: ItemButtonProps) {
  return <button onClick={() => onSelect(id)}>Select</button>;
}

When handling more complex events, such as form submissions or changes, you can use React’s built-in event types:

type FormProps = {
  onSubmit: (event: React.FormEvent<HTMLFormElement>) => void;
};

function MyForm({ onSubmit }: FormProps) {
  return <form onSubmit={onSubmit}>...</form>;
}

Typing callback props this way ensures that the parent provides a function with the correct signature, and that the child component calls it with the right arguments. This pattern is essential for robust event handling and clear data flow in React apps.

Another advanced pattern in React is the use of higher-order functions, such as higher-order components (HOCs) or functions that enhance or wrap other components. Typing these correctly in TypeScript is crucial to maintain type safety, especially when passing props through layers of abstraction.

A higher-order function in React might look like a function that takes a component and returns a new component with extra functionality. To type this, you can use generics to capture the props of the original component and pass them through:

import React from "react";

// A higher-order function that adds logging to a component
function withLogger<P>(Component: React.ComponentType<P>) {
  return function LoggedComponent(props: P) {
    console.log("Props:", props);
    return <Component {...props} />;
  };
}

// Usage
type UserProps = { name: string };
function User({ name }: UserProps) {
  return <div>{name}</div>;
}

const UserWithLogger = withLogger(User);
// UserWithLogger is now typed to accept UserProps

By using a generic type P, the withLogger function ensures that the returned component expects the same props as the original. This pattern can be extended to more complex cases, such as injecting additional props or modifying the behavior of the component.

Typing higher-order functions in this way ensures that TypeScript can check the correctness of props throughout your component tree, preventing subtle bugs and improving maintainability.

1. What is a callback prop in React?

2. Why is it important to type higher-order functions in React?

question mark

What is a callback prop in React?

Select the correct answer

question mark

Why is it important to type higher-order functions in React?

Select the correct answer

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 6. Capitolo 4

Chieda ad AI

expand

Chieda ad AI

ChatGPT

Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione

Awesome!

Completion rate improved to 4.17

bookTyping Higher-Order Functions and Callback Props

Scorri per mostrare il menu

When you build React components, you often need to pass functions as props so that child components can notify parents of events, changes, or actions. These are called callback props. Typing callback props precisely in TypeScript helps ensure your components interact correctly and safely, catching possible errors at compile time.

Suppose you have a button component that notifies its parent when it is clicked. You can define the callback prop with a function type that matches the expected signature. For a simple click with no arguments:

type ButtonProps = {
  onClick: () => void;
};

function Button({ onClick }: ButtonProps) {
  return <button onClick={onClick}>Click me</button>;
}

If the callback should receive data, such as an item ID, you can specify the type of the argument:

type ItemButtonProps = {
  onSelect: (id: string) => void;
  id: string;
};

function ItemButton({ onSelect, id }: ItemButtonProps) {
  return <button onClick={() => onSelect(id)}>Select</button>;
}

When handling more complex events, such as form submissions or changes, you can use React’s built-in event types:

type FormProps = {
  onSubmit: (event: React.FormEvent<HTMLFormElement>) => void;
};

function MyForm({ onSubmit }: FormProps) {
  return <form onSubmit={onSubmit}>...</form>;
}

Typing callback props this way ensures that the parent provides a function with the correct signature, and that the child component calls it with the right arguments. This pattern is essential for robust event handling and clear data flow in React apps.

Another advanced pattern in React is the use of higher-order functions, such as higher-order components (HOCs) or functions that enhance or wrap other components. Typing these correctly in TypeScript is crucial to maintain type safety, especially when passing props through layers of abstraction.

A higher-order function in React might look like a function that takes a component and returns a new component with extra functionality. To type this, you can use generics to capture the props of the original component and pass them through:

import React from "react";

// A higher-order function that adds logging to a component
function withLogger<P>(Component: React.ComponentType<P>) {
  return function LoggedComponent(props: P) {
    console.log("Props:", props);
    return <Component {...props} />;
  };
}

// Usage
type UserProps = { name: string };
function User({ name }: UserProps) {
  return <div>{name}</div>;
}

const UserWithLogger = withLogger(User);
// UserWithLogger is now typed to accept UserProps

By using a generic type P, the withLogger function ensures that the returned component expects the same props as the original. This pattern can be extended to more complex cases, such as injecting additional props or modifying the behavior of the component.

Typing higher-order functions in this way ensures that TypeScript can check the correctness of props throughout your component tree, preventing subtle bugs and improving maintainability.

1. What is a callback prop in React?

2. Why is it important to type higher-order functions in React?

question mark

What is a callback prop in React?

Select the correct answer

question mark

Why is it important to type higher-order functions in React?

Select the correct answer

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 6. Capitolo 4
some-alt