Skip to main content

Custom Hooks in TypeScript

Level: Beginner to Intermediate

ℹ️ What You'll Learn
  • What Custom Hooks in TypeScript means in React + TypeScript
  • How type safety improves React components
  • How to model School Management System data with interfaces and types
  • Common TypeScript mistakes to avoid
  • How to explain this topic in interviews

Why This Matters

Custom Hooks in TypeScript helps you build React screens with fewer runtime bugs. In real .NET Web API projects, TypeScript makes API DTOs, component props, form state, and shared data contracts easier to understand and safer to change.

Type custom hooks for reusable, type-safe logic across components.

Prerequisite: Read React JS article 15 first.

The Problem

React JavaScript can fail at runtime when props, API responses, or form values have the wrong shape. This lesson shows how Custom Hooks in TypeScript uses TypeScript to catch many of those mistakes while you write code, before the student dashboard reaches users.

Generic useFetch Hook

interface FetchState<T> {
data: T | null;
loading: boolean;
error: Error | null;
}

function useFetch<T>(url: string): FetchState<T> {
const [state, setState] = useState<FetchState<T>>({
data: null,
loading: true,
error: null
});

useEffect(() => {
let isMounted = true;

fetch(url)
.then(r => r.json())
.then((data: T) => {
if (isMounted) setState({ data, loading: false, error: null });
})
.catch((error: unknown) => {
if (isMounted) {
const err = error instanceof Error ? error : new Error('Unknown');
setState({ data: null, loading: false, error: err });
}
});

return () => {
isMounted = false;
};
}, [url]);

return state;
}

// Usage
function StudentList() {
const { data: students, loading, error } = useFetch<Student[]>('/api/students');

if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;
return <ul>{students?.map(s => <li key={s.id}>{s.name}</li>)}</ul>;
}

useRef with DOM Types

function StudentSearchInput() {
const inputRef = useRef<HTMLInputElement>(null);
const searchRef = useRef<HTMLDivElement>(null);

const focus = (): void => {
inputRef.current?.focus();
};

const getSearchValue = (): string => {
return inputRef.current?.value || '';
};

return (
<div ref={searchRef}>
<input ref={inputRef} type="text" placeholder="Search..." />
<button onClick={focus}>Focus</button>
<button onClick={() => console.log(getSearchValue())}>Get Value</button>
</div>
);
}

useForm Hook with Types

interface UseFormOptions<T> {
initialValues: T;
onSubmit: (values: T) => Promise<void>;
validate?: (values: T) => Partial<Record<keyof T, string>>;
}

interface UseFormResult<T> {
values: T;
errors: Partial<Record<keyof T, string>>;
handleChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
handleSubmit: (e: React.FormEvent<HTMLFormElement>) => Promise<void>;
isSubmitting: boolean;
}

function useForm<T extends Record<string, any>>({
initialValues,
onSubmit,
validate
}: UseFormOptions<T>): UseFormResult<T> {
const [values, setValues] = useState<T>(initialValues);
const [errors, setErrors] = useState<Partial<Record<keyof T, string>>>({});
const [isSubmitting, setIsSubmitting] = useState(false);

const handleChange = (e: React.ChangeEvent<HTMLInputElement>): void => {
const { name, value } = e.target;
setValues(prev => ({
...prev,
[name]: value
}));
};

const handleSubmit = async (e: React.FormEvent<HTMLFormElement>): Promise<void> => {
e.preventDefault();

if (validate) {
const newErrors = validate(values);
if (Object.keys(newErrors).length > 0) {
setErrors(newErrors);
return;
}
}

setIsSubmitting(true);
try {
await onSubmit(values);
} finally {
setIsSubmitting(false);
}
};

return {
values,
errors,
handleChange,
handleSubmit,
isSubmitting
};
}

// Usage
interface LoginForm {
email: string;
password: string;
}

function LoginForm() {
const { values, errors, handleChange, handleSubmit, isSubmitting } =
useForm<LoginForm>({
initialValues: { email: '', password: '' },
onSubmit: async (values) => {
await fetch('/api/login', {
method: 'POST',
body: JSON.stringify(values)
});
},
validate: (values) => {
const errors: Partial<Record<keyof LoginForm, string>> = {};
if (!values.email) errors.email = 'Required';
if (!values.password) errors.password = 'Required';
return errors;
}
});

return (
<form onSubmit={handleSubmit}>
<input name="email" value={values.email} onChange={handleChange} />
{errors.email && <p>{errors.email}</p>}
<input name="password" type="password" value={values.password} onChange={handleChange} />
{errors.password && <p>{errors.password}</p>}
<button disabled={isSubmitting} type="submit">Login</button>
</form>
);
}

useCallback Hook

interface Student {
id: number;
name: string;
}

interface UseStudentActionsResult {
students: Student[];
addStudent: (name: string) => void;
removeStudent: (id: number) => void;
}

function useStudentActions(): UseStudentActionsResult {
const [students, setStudents] = useState<Student[]>([]);

const addStudent = useCallback((name: string): void => {
setStudents(prev => [...prev, {
id: Date.now(),
name
}]);
}, []);

const removeStudent = useCallback((id: number): void => {
setStudents(prev => prev.filter(s => s.id !== id));
}, []);

return { students, addStudent, removeStudent };
}

Key Takeaways

  • Generic hooks with <T>
  • Type useRef with HTML elements
  • useForm hook for forms
  • useCallback for stable functions
  • Reusable across components
  • Next: Best practices
⚠️ Hook Mistakes
  1. Not typing generics — Hook can't be used properly
  2. Wrong ref typeuseRef<HTMLInputElement> not HTMLDivElement
  3. Missing dependencies — useCallback dependencies
  4. Async in hook directly — Create async function inside
💡 Hook File Organization
hooks/
├── useFetch.ts
├── useForm.ts
├── useStudentActions.ts
└── index.ts (export all)
🤖Use AI to Learn Faster

Use ChatGPT, Claude, or Copilot to go deeper on Typed Hooks. Try these prompts:

  • "How do you type generic hooks?"
  • "What's the type of useRef for inputs?"
  • "When use useCallback in hooks?"
  • "Quiz me on custom hook types"

💡 Tip: After reading this article, paste your own code into AI and ask "What could go wrong here and why?" — fastest way to find edge cases and deepen understanding.

Quick Definitions

  • Custom Hooks in TypeScript - The main React + TypeScript concept explained in this lesson.
  • Type/interface - A contract that describes the shape of data.
  • Typed props/state - React data with clear compile-time expectations.
  • API DTO - The request or response shape shared with ASP.NET Core Web API.

Common Mistakes

  • Using any too quickly instead of defining a useful type
  • Typing props loosely and losing the benefit of TypeScript
  • Forgetting that API data can still be missing or invalid at runtime
  • Making types too complex before the component is stable
  • Not sharing clear DTO shapes between frontend and backend teams

Practice Task

Create a small React TypeScript example using Custom Hooks in TypeScript. Keep it connected to a School Management System scenario.

Suggested practice:

  1. Define a clear Student, Teacher, or Attendance type.
  2. Build a small typed component or hook.
  3. Add one valid example and one intentionally wrong example to see TypeScript errors.
  4. Explain the type contract in your own words.
  5. Rebuild the same example once without looking at the article.

Quick Revision

QuestionAnswer
What is the main idea?Use TypeScript to make Custom Hooks in TypeScript safer in React.
Where is it used?Props, state, forms, API responses, context, hooks, and routes.
What should beginners avoid?Overusing any and ignoring runtime API validation.
What is the best debugging habit?Read the TypeScript error, check the data shape, and fix the type contract.
🎯 How would you explain Custom Hooks in TypeScript in an interview?

Custom Hooks in TypeScript is a React + TypeScript concept that improves safety and maintainability. I would explain which values need types, how TypeScript catches mistakes early, and how it helps when consuming ASP.NET Core Web API responses.

🎯 Where is this used in a real React TypeScript project?

It is used in typed props, API response models, form state, route parameters, context values, custom hooks, and reusable UI components.

Next Article

Best Practices in TypeScript ->

nexcoding.in