Dev.to WebDev πŸ›  Dev πŸ‘ 0 πŸ“– 8 min read

Best Practices for Using TypeScript with React

Originally published on Medium (JavaScript in Plain English). Read on Medium for free via Friend Link. ⚑ Get the Production-Ready React Hooks Pack Β· πŸ“¦ Sample Repo on GitHub Quick Takeaways Component & Pro

Best Practices for Using TypeScript with React

Originally published on Medium (JavaScript in Plain English). Read on Medium for free via Friend Link.

⚑ Get the Production-Ready React Hooks Pack Β· πŸ“¦ Sample Repo on GitHub

Quick Takeaways

  • Component & Prop Typing : Use PropsWithChildren, ComponentProps, Pick, and ComponentType to keep component APIs strict without duplicating type definitions.
  • Predictable State : Let useState infer simple primitives, explicitly type nullable or union states, and use discriminated unions with useReducer.
  • Safe DOM & Component Refs : Initialize DOM refs with null (useRef<HTMLInputElement | null>(null)) and forward refs cleanly with forwardRef.
  • Typed Event Handlers : Rely on React's MouseEventHandler for component events and native Event types for global window listeners.

Using TypeScript with React can feel daunting at first. However, with the right patterns, the compiler stops feeling like an obstacle and starts acting like a safety net that catches bugs before they hit production. This guide covers practical best practices for integrating TypeScript into React projects, broken into four key sections: components, state management, refs, and events.

TypeScript and React logos side by side representing type-safe React development
TypeScript and React β€” building predictable, type-safe UI components at scale.

Learn how to effectively integrate TypeScript with React for better type safety, state management, and event handling. Check out the full implementation on GitHub here.

Components

Defining Basic Props

React components are typically written as functions that accept a props object. With TypeScript, you define the exact shape of that object so invalid or missing props fail at compile time.

type BookProps = {
  name: string;
  author?: string; // Optional prop
};

function BookInfo({ name, author }: BookProps) {
  return (
    <div>
      <h2>{name}</h2>
      {author && <p>Author: {author}</p>}
    </div>
  );
}

Handling children Props

React lets you compose components by passing JSX via children. You can type these props cleanly using React's built-in PropsWithChildren utility.

import { PropsWithChildren } from 'react';

type CourseProps = {
  courseName: string;
};

function CourseInfo({
  courseName,
  children,
}: PropsWithChildren<CourseProps>) {
  return (
    <div>
      <h1>{courseName}</h1>
      {children}
    </div>
  );
}

Tip : If your component only accepts children and no custom props, you can use PropsWithChildren directly without defining an extra type.

Passing and Forwarding Props

Components often need to pass props down to child components. TypeScript's ComponentProps utility extracts a component's prop types directly, keeping types in sync without repetition.

import { ComponentProps } from 'react';
import BookInfo from './BookInfo';

type BookInfoProps = ComponentProps<typeof BookInfo>;

type Props = {
  themeColor: string;
  title: BookInfoProps['title'];
};

function FeaturedBookInfo({ themeColor, title }: Props) {
  return (
    <div style={{ background: themeColor }}>
      <BookInfo title={title} />
    </div>
  );
}

If BookInfo's props change later, TypeScript immediately flags any mismatch in FeaturedBookInfo, reducing maintenance overhead.

Spreading Props

Spreading props forwards all props of a wrapper component down to its child. It is especially useful when wrapping existing components with extra styling or behavior without repeating every prop definition.

import { ComponentProps } from 'react';
import BookInfo from './BookInfo';

type Props = {
  themeColor: string;
} & ComponentProps<typeof BookInfo>;

function HighlightedBookInfo({
  themeColor,
  ...props
}: Props) {
  return (
    <div style={{ background: themeColor }}>
      <BookInfo {...props} />
    </div>
  );
}

Any updates or new props added to BookInfo automatically propagate to HighlightedBookInfo. If you only want to forward a subset of props, combine ComponentProps with TypeScript's Pick utility:

import { ComponentProps } from 'react';
import CourseInfo from './CourseInfo';

type CourseInfoProps = ComponentProps<typeof CourseInfo>;

type Props = {
  themeColor: string;
} & Pick<
  CourseInfoProps,
  'courseTitle' | 'courseDuration'
>;

function FeaturedCourseInfo({
  themeColor,
  ...props
}: Props) {
  return (
    <div style={{ background: themeColor }}>
      <CourseInfo {...props} />
    </div>
  );
}

Here, only courseTitle and courseDuration are exposed and forwarded to CourseInfo.

Prop Forwarding for HTML Elements

The same pattern works for native HTML elements. Using ComponentProps<'button'> gives you type-safe access to every valid button attribute, including onClick, disabled, and type.

import { ComponentProps } from 'react';

type ButtonProps = ComponentProps<'button'>;

function CustomButton(props: ButtonProps) {
  return <button {...props} />;
}

ComponentProps<'button'> is shorter and more readable than React.JSX.IntrinsicElements['button']. If you ever need to exclude React-specific props like ref or key, you can use React.ButtonHTMLAttributes<HTMLButtonElement> instead.

Passing JSX (ReactNode)

Beyond primitive values, you often want to pass raw JSX into named slotsβ€”such as a custom sidebar or navigation menuβ€”using ReactNode.

import { PropsWithChildren, ReactNode } from 'react';

type DashboardProps = {
  title: string;
  menu: ReactNode;
};

function Dashboard({
  title,
  children,
  menu,
}: PropsWithChildren<DashboardProps>) {
  return (
    <div className="dashboard">
      <aside className="menu">{menu}</aside>
      <section className="main-content">
        <h1>{title}</h1>
        {children}
      </section>
    </div>
  );
}

const menu = (
  <nav>
    <a href="/profile">Profile</a>
    <a href="/settings">Settings</a>
    <a href="/logout">Logout</a>
  </nav>
);

const App = (
  <Dashboard title="User Dashboard" menu={menu}>
    {/* Dashboard content */}
  </Dashboard>
);

Because ReactNode accepts elements, strings, numbers, fragments, and null, it covers every valid renderable value in React.

Passing Components (ComponentType)

When you need to pass an entire component as a propβ€”for example, a custom renderer or dynamic cardβ€”use ComponentType<Props>.

import { ComponentType } from 'react';

type BookDetailProps = {
  title: string;
  genre?: string;
};

type DynamicBookProps = {
  render: ComponentType<BookDetailProps>;
};

function BookDetail({ render: Render }: DynamicBookProps) {
  const props = {
    title: 'Moby Dick',
    genre: 'Adventure',
  };

  return <Render {...props} />;
}

This lets the parent pass any component that matches BookDetailProps, giving you flexibility without sacrificing type safety.

Passing Specific Components Using typeof

When a prop should accept only a specific component (or a structurally identical one), type it with typeof.

import { ComponentProps } from 'react';
import Icon from './Icon';

type Props = {
  icon?: typeof Icon;
} & ComponentProps<'button'>;

function Button({
  icon: IconComp,
  children,
  ...props
}: Props) {
  return (
    <button {...props}>
      {IconComp && <IconComp size={24} />}
      {children}
    </button>
  );
}

Using typeof Icon restricts the icon prop to components compatible with Icon's exact signature.

Inferring Props with Polymorphic Components

Component libraries often infer valid props dynamically based on an as prop. For instance, passing as="input" unlocks value, while as="div" rejects it at compile time:

const App = (
  <>
    {/* Error: div does not have a value prop */}
    <Box as="div" value="foo" />

    {/* Valid: input supports the value prop */}
    <Box as="input" value="foo" />
  </>
);

By combining ComponentProps, Pick, ReactNode, and ComponentType, you can build flexible, reusable component APIs with minimal boilerplate.

State Management

Using useState

TypeScript infers types automatically from simple initial values like numbers or booleans. For nullable values, arrays, or union types, provide the type explicitly via a generic parameter.

import { useState } from 'react';

type Todo = {
  id: string;
  title: string;
  completed: boolean;
};

function TodoList() {
  const [todos, setTodos] = useState<Todo[] | null>(null);

  return <div>{todos?.length ?? 0} todos</div>;
}

Using useReducer

For state transitions with multiple actions, useReducer paired with a discriminated union for Action ensures every dispatch call is checked against valid payloads.

import { useReducer } from 'react';

type State = number;
type Action =
  | { type: 'increment' }
  | { type: 'decrement' }
  | { type: 'reset'; payload: number };

function reducer(state: State, action: Action): State {
  switch (action.type) {
    case 'increment':
      return state + 1;
    case 'decrement':
      return state - 1;
    case 'reset':
      return action.payload;
    default:
      throw new Error('Unhandled action type');
  }
}

function Counter() {
  const [count, dispatch] = useReducer(reducer, 0);

  return (
    <div>
      <p>Count: {count}</p>
      <button
        onClick={() => dispatch({ type: 'increment' })}
      >
        Increment
      </button>
    </div>
  );
}

Working with Refs

Refs give you direct access to DOM nodes or imperative component handles. Typing them accurately prevents runtime null-reference errors.

Creating DOM Refs

Pass the HTML element type to useRef and initialize it with null, then use optional chaining (?.) when accessing .current.

import { useRef } from 'react';

function FocusableInput() {
  const inputRef = useRef<HTMLInputElement | null>(null);

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

  return (
    <div>
      <input ref={inputRef} type="text" />
      <button onClick={focusInput}>Focus</button>
    </div>
  );
}

Forwarding Refs

When a parent component needs access to a child's underlying DOM element, wrap the child with forwardRef and specify both the element type and props type.

import { forwardRef } from 'react';

type ButtonProps = {
  label: string;
};

const FancyButton = forwardRef<
  HTMLButtonElement,
  ButtonProps
>(({ label }, ref) => {
  return <button ref={ref}>{label}</button>;
});

Event Handling

React wraps native browser events in SyntheticEvent types. Using React's built-in handler types guarantees that event.target and event.currentTarget are typed accurately.

Handling DOM Events

For component event props, use handler types such as MouseEventHandler<HTMLButtonElement>.

import { MouseEventHandler } from 'react';

type ButtonProps = {
  onClick: MouseEventHandler<HTMLButtonElement>;
};

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

Adding Global Event Listeners

When attaching listeners directly to window or document inside useEffect, use native DOM Event types rather than React synthetic event types.

import { useEffect } from 'react';

function ScrollListener() {
  useEffect(() => {
    const handleScroll = (event: Event) => {
      console.log('Page scrolled', event.timeStamp);
    };

    window.addEventListener('scroll', handleScroll);
    return () => {
      window.removeEventListener('scroll', handleScroll);
    };
  }, []);

  return <div>Scroll to see console logs.</div>;
}

Final Thoughts

TypeScript and React work best together when you let inference do the heavy lifting and reach for utility types like ComponentProps, PropsWithChildren, and discriminated unions where boundaries matter. Start small, keep your component contracts explicit, and the compiler will pay you back every time you refactor.

Check out the full working examples in the accompanying GitHub repository: react-typescript-sample.

Which TypeScript + React pattern saved you the most debugging time in production? I'd love to hear your thoughts πŸ§ πŸ’¬

Keep Exploring

Mustafa Morbel is a software engineer with over 17 years of experience building web applications, frontend architectures, and developer tools.

πŸ“° Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.