React lets you define components as classes or functions. Components defined as classes currently provide more features which are described in detail on this page. To define a React component class, you need to extend React.Component:

class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}
To use JSX-support with React you should use the React typings. These typings define the JSX namespace so that TypeScript can correctly check JSX expressions for React. For example:

ts
/// <reference path="react.d.ts" />interface Props {  name: string;}class MyComponent extends React.Component<Props, {}> {  render() {    return <span>{this.props.foo}</span>;  }}<MyComponent name="bar" />; // OK<MyComponent name={0} />; // error, `name` is not a number
In short using this general type, we can model React’s specific behavior for things like defaultProps and, to some extent, propTypes.

tsx
export interface Props {  name: string;}export class Greet extends React.Component<Props> {  render() {    const { name } = this.props;    return <div>Hello ${name.toUpperCase()}!</div>;  }  static defaultProps = { name: "world" };}// Type-checks! No type assertions needed!let el = <Greet />;
JSX elements now allow passing type arguments to generic components.

ts
class GenericComponent<P> extends React.Component<P> {  internalProp: P;}type Props = { a: number; b: string };const x = <GenericComponent<Props> a={10} b="hi" />; // OKconst y = <GenericComponent<Props> a={10} b={20} />; // Error
For example, this component sets the document title after React updates the DOM:

import React, { useState, useEffect } from 'react';
function Example() {
  const [count, setCount] = useState(0);

  // Similar to componentDidMount and componentDidUpdate:  useEffect(() => {    // Update the document title using the browser API    document.title = `You clicked ${count} times`;  });
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}
Effects may also optionally specify how to “clean up” after them by returning a function. For example, this component uses an effect to subscribe to a friend’s online status, and cleans up by unsubscribing from it:

import React, { useState, useEffect } from 'react';

function FriendStatus(props) {
  const [isOnline, setIsOnline] = useState(null);

  function handleStatusChange(status) {
    setIsOnline(status.isOnline);
  }

  useEffect(() => {    ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);    return () => {      ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);    };  });
  if (isOnline === null) {
    return 'Loading...';
  }
  return isOnline ? 'Online' : 'Offline';
}
In addition to compositional patterns like the above, this new inference on generic constructors means that functions that operate on class components in certain UI libraries like React can more correctly operate on generic class components.

ts
type ComponentClass<P> = new (props: P) => Component<P>;declare class Component<P> {  props: P;  constructor(props: P);}declare function myHoc<P>(C: ComponentClass<P>): ComponentClass<P>;type NestedProps<T> = { foo: number; stuff: T };declare class GenericComponent<T> extends Component<NestedProps<T>> {}// type is 'new <T>(props: NestedProps<T>) => Component<NestedProps<T>>'const GenericComponent2 = myHoc(GenericComponent);
TypeScript now supports Stateless Function components. These are lightweight components that easily compose other components:

ts
// Use parameter destructuring and defaults for easy definition of 'props' typeconst Greeter = ({ name = "world" }) => <div>Hello, {name}!</div>;// Properties get validatedlet example = <Greeter name="TypeScript 1.8" />;
To address this pattern, React introduced the React.Fragment component, which provides a dedicated way to wrap such elements without adding an element to the DOM. Correspondingly, the <>... syntax was added to JSX to facilitate this new construct. Therefore, the above scenario becomes:

tsx
render() {    return (        <>            Some text.            <h2>A heading</h2>            More text.        </>    );}
You can use the State Hook more than once in a single component:

function ExampleWithManyStates() {
  // Declare multiple state variables!
  const [age, setAge] = useState(42);
  const [fruit, setFruit] = useState('banana');
  const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]);
  // ...
}

Recommend

Render Props Caveats Be careful when using Render Props with React.PureComponent

React Render Props Using Props Other Than render

React Render Props Use Render Props for Cross-Cutting Concerns

React Render Props

React Hooks FAQ Performance Optimizations How to read an often-changing value from useCallback?

React Hooks FAQ Performance Optimizations How to avoid passing callbacks down?

React Hooks FAQ Performance Optimizations Are Hooks slow because of creating functions in render?

React Hooks FAQ Performance Optimizations How to create expensive objects lazily?

React Hooks FAQ Performance Optimizations How to memoize calculations?

React Hooks FAQ Performance Optimizations How do I implement shouldComponentUpdate?

React Hooks FAQ Performance Optimizations What can I do if my effect dependencies change too often?

React Hooks FAQ Performance Optimizations Is it safe to omit functions from the list of dependencies?

React Hooks FAQ From Classes to Hooks How can I measure a DOM node?

React Hooks FAQ From Classes to Hooks Is there something like forceUpdate?

React Hooks FAQ From Classes to Hooks How do I implement getDerivedStateFromProps?

React Hooks FAQ From Classes to Hooks Why am I seeing stale props or state inside my function?

React Hooks FAQ From Classes to Hooks How to get the previous props or state?

React Hooks FAQ From Classes to Hooks Should I use one or many state variables?

React Hooks FAQ From Classes to Hooks Is there something like instance variables?

React Hooks FAQ Adoption Strategy How to test components that use Hooks?

React Forms Controlled Input Null Value

React Forms Handling Multiple Inputs

React Forms The file input Tag

React Forms The select Tag

React Forms The textarea Tag

React Forms Controlled Components

React Forms

Thinking in React Start With A Mock

React Typechecking With PropTypes Function Components

React Typechecking With PropTypes Default Prop Values

React Typechecking With PropTypes Requiring Single Child

React Typechecking With PropTypes PropTypes

React Typechecking With PropTypes

React Lifting State Up Lifting State Up

React Lifting State Up Writing Conversion Functions

React Lifting State Up Adding a Second Input

React Lifting State Up

ReactDOM Reference createPortal()

ReactDOM Reference findDOMNode()

ReactDOM Reference unmountComponentAtNode()

ReactDOM Reference hydrate()

ReactDOM Reference render()

React Release Channels Next Channel Using the Next Channel for Integration Testing

React Uncontrolled Components The file input Tag

React Uncontrolled Components Default Values

React Uncontrolled Components

React CDN Links Why the crossorigin Attribute?

React CDN Links

React Forwarding Refs Displaying a custom name in DevTools