Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте Typed Return Values | Typing Custom Hooks
Quizzes & Challenges
Quizzes
Challenges
/
TypeScript Essentials for React

bookTyped Return Values

Typed custom hooks are a powerful pattern in React, allowing you to encapsulate logic and reuse it across your application. When you create hooks that return complex values—such as objects, arrays, or tuples—typing these return values correctly is crucial for both safety and developer experience. You want consumers of your hook to immediately know what to expect, making your hooks both robust and easy to use.

Consider a hook that returns an object. You might create a hook for toggling boolean state:

function useToggle(initial: boolean) {
  const [value, setValue] = React.useState(initial);
  const toggle = () => setValue(v => !v);
  return { value, toggle };
}

// Typed return value:
type UseToggleReturn = {
  value: boolean;
  toggle: () => void;
};

function useToggleTyped(initial: boolean): UseToggleReturn {
  const [value, setValue] = React.useState(initial);
  const toggle = () => setValue(v => !v);
  return { value, toggle };
}

When your hook returns an array, you can specify the type as an array or a tuple. Arrays are useful for lists of items of the same type, while tuples are ideal when the array has a fixed length and each position has a specific meaning. For example, a hook that returns a value and a setter is best typed as a tuple:

function useCounter(initial: number): [number, () => void] {
  const [count, setCount] = React.useState(initial);
  const increment = () => setCount(c => c + 1);
  return [count, increment];
}
type FetchResult<T> = [T | null, boolean, Error | null];

function useFetch<T>(url: string): FetchResult<T> {
  const [data, setData] = React.useState<T | null>(null);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState<Error | null>(null);

  React.useEffect(() => {
    setLoading(true);
    fetch(url)
      .then(res => res.json())
      .then(setData)
      .catch(setError)
      .finally(() => setLoading(false));
  }, [url]);

  return [data, loading, error];
}

When documenting your custom hooks, always specify the return type in your TypeScript signature. This makes it clear to consumers what the hook provides. If your hook is generic, define a generic return type. For objects, use interfaces or type aliases for clarity. For tuples, type each position explicitly. Good documentation and explicit return types help TypeScript infer types for consumers, leading to better autocomplete, fewer errors, and a smoother development experience.

1. Why is it important to type the return value of a custom hook?

2. Which of the following is a valid way to type a hook returning a tuple?

question mark

Why is it important to type the return value of a custom hook?

Select the correct answer

question mark

Which of the following is a valid way to type a hook returning a tuple?

Select the correct answer

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 5. Розділ 3

Запитати АІ

expand

Запитати АІ

ChatGPT

Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат

Suggested prompts:

Can you explain the difference between using an array and a tuple as a return type in hooks?

How do I document a generic custom hook's return type effectively?

Can you show more examples of typing complex hook return values?

Awesome!

Completion rate improved to 4.17

bookTyped Return Values

Свайпніть щоб показати меню

Typed custom hooks are a powerful pattern in React, allowing you to encapsulate logic and reuse it across your application. When you create hooks that return complex values—such as objects, arrays, or tuples—typing these return values correctly is crucial for both safety and developer experience. You want consumers of your hook to immediately know what to expect, making your hooks both robust and easy to use.

Consider a hook that returns an object. You might create a hook for toggling boolean state:

function useToggle(initial: boolean) {
  const [value, setValue] = React.useState(initial);
  const toggle = () => setValue(v => !v);
  return { value, toggle };
}

// Typed return value:
type UseToggleReturn = {
  value: boolean;
  toggle: () => void;
};

function useToggleTyped(initial: boolean): UseToggleReturn {
  const [value, setValue] = React.useState(initial);
  const toggle = () => setValue(v => !v);
  return { value, toggle };
}

When your hook returns an array, you can specify the type as an array or a tuple. Arrays are useful for lists of items of the same type, while tuples are ideal when the array has a fixed length and each position has a specific meaning. For example, a hook that returns a value and a setter is best typed as a tuple:

function useCounter(initial: number): [number, () => void] {
  const [count, setCount] = React.useState(initial);
  const increment = () => setCount(c => c + 1);
  return [count, increment];
}
type FetchResult<T> = [T | null, boolean, Error | null];

function useFetch<T>(url: string): FetchResult<T> {
  const [data, setData] = React.useState<T | null>(null);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState<Error | null>(null);

  React.useEffect(() => {
    setLoading(true);
    fetch(url)
      .then(res => res.json())
      .then(setData)
      .catch(setError)
      .finally(() => setLoading(false));
  }, [url]);

  return [data, loading, error];
}

When documenting your custom hooks, always specify the return type in your TypeScript signature. This makes it clear to consumers what the hook provides. If your hook is generic, define a generic return type. For objects, use interfaces or type aliases for clarity. For tuples, type each position explicitly. Good documentation and explicit return types help TypeScript infer types for consumers, leading to better autocomplete, fewer errors, and a smoother development experience.

1. Why is it important to type the return value of a custom hook?

2. Which of the following is a valid way to type a hook returning a tuple?

question mark

Why is it important to type the return value of a custom hook?

Select the correct answer

question mark

Which of the following is a valid way to type a hook returning a tuple?

Select the correct answer

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 5. Розділ 3
some-alt