Skip to content

React TypeScript

React with TypeScript, using pnpm and Vite, provides a modern, efficient, and powerful stack for building web applications. I'll break down the explanation into several parts, covering the setup process and diving into React hooks with TypeScript examples.

Setting Up a React + TypeScript Project with pnpm and Vite

  1. Install pnpm
    Ensure you have Node.js installed on your machine. Install pnpm globally via your terminal with:

    bash
    npm install -g pnpm
  2. Create a New Project with Vite
    Vite is a build tool that significantly improves the frontend development experience. To create a new React project with TypeScript using Vite, run:

    bash
    pnpm create vite my-react-ts-app -- --template react-ts

    Replace my-react-ts-app with your desired project name. This command creates a new directory with a React + TypeScript setup.

  3. Navigate and Install Dependencies
    Change into your project directory and install dependencies:

    bash
    cd my-react-ts-app
    pnpm install
  4. Start the Development Server
    To start the development server, run:

    bash
    pnpm run dev

    Your new React app should now be accessible at http://localhost:3000.

React Hooks with TypeScript

React hooks are functions that let you “hook into” React state and lifecycle features from function components. Here are examples of common hooks in React with TypeScript annotations:

useState

The useState hook lets you add React state to function components.

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

function Counter() {
  const [count, setCount] = useState<number>(0); // `count` is of type number

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
}

useEffect

The useEffect hook lets you perform side effects in function components.

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

function Example() {
  const [count, setCount] = useState<number>(0);

  useEffect(() => {
    document.title = `You clicked ${count} times`;
  }, [count]); // Only re-run the effect if `count` changes

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
}

useContext

The useContext hook lets you subscribe to React context without introducing nesting.

tsx
import React, { useContext } from 'react';

const ThemeContext = React.createContext('light');

function ThemedButton() {
  const theme = useContext(ThemeContext); // `theme` is of the context value's type
  return <button className={theme}>I am styled by theme context!</button>;
}

useReducer

useReducer is usually preferable to useState when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one.

tsx
import React, { useReducer } from 'react';

type CounterState = {
  count: number;
};

type CounterAction = {
  type: 'increment' | 'decrement';
};

function reducer(state: CounterState, action: CounterAction): CounterState {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 };
    case 'decrement':
      return { count: state.count - 1 };
    default:
      throw new Error();
  }
}

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

  return (
    <>
      Count: {state.count}
      <button onClick={() => dispatch({ type: 'decrement' })}>-</button>
      <button onClick={() => dispatch({ type: 'increment' })}>+</button>
    </>
  );
}

Conclusion

This overview provides a basic foundation for starting a React project with TypeScript using pnpm and Vite, along with examples of common React hooks. These hooks are crucial for managing state, effects, context, and more complex state logic in your React applications. Remember, TypeScript adds type safety to your React components and hooks, greatly enhancing development productivity and maintainability.

Contributors

No contributors

Changelog

No recent changes