Skip to content

React Installation

Overview

This chapter will detail how to set up a React development environment, including Node.js installation, development tool configuration, creating your first React project, and more. We will learn multiple ways to create React projects, as well as necessary development tool installations.

🛠️ Prerequisites

Required Software

Node.js and npm

bash
# Check if Node.js is installed
node --version
# Should display: v18.0.0 or higher

# Check npm version
npm --version
# Should display: 8.0.0 or higher

Recommended Configuration:

  • Node.js 18.0+ or 20.0+ (LTS version)
  • npm 8.0+ or yarn 1.22+
  • Modern browsers (Chrome, Firefox, Safari, Edge)

Optional Tools

  • Git: Version control
  • VS Code: Recommended code editor
  • Chrome DevTools: Debugging tools

📥 Node.js Installation

Windows Systems

bash
# Method 1: Download from official website
# Visit https://nodejs.org/
# Download LTS version and install

# Method 2: Use Chocolatey
choco install nodejs

# Method 3: Use Scoop
scoop install nodejs

macOS Systems

bash
# Method 1: Download from official website
# Visit https://nodejs.org/

# Method 2: Use Homebrew
brew install node

# Method 3: Use MacPorts
sudo port install nodejs18

Linux Systems

bash
# Ubuntu/Debian
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt-get install -y nodejs

# CentOS/RHEL/Fedora
curl -fsSL https://rpm.nodesource.com/setup_18.x | sudo bash -
sudo dnf install -y nodejs

# Arch Linux
sudo pacman -S nodejs npm

Verifying Installation

bash
# Check versions
node --version
npm --version

# Check npm global package location
npm config get prefix

# Update npm to latest version
npm install -g npm@latest

🚀 Creating React Projects

Installation and project creation:

bash
# Using npx (recommended)
npx create-react-app my-react-app

# Or install globally first then use
npm install -g create-react-app
create-react-app my-react-app

# Enter project directory
cd my-react-app

# Start development server
npm start

Project Structure:

my-react-app/
├── public/
│   ├── index.html
│   ├── favicon.ico
│   └── manifest.json
├── src/
│   ├── App.js
│   ├── App.css
│   ├── index.js
│   ├── index.css
│   └── App.test.js
├── package.json
├── README.md
└── yarn.lock

Creating a project:

bash
# Using npm
npm create vite@latest my-react-app -- --template react

# Using yarn
yarn create vite my-react-app --template react

# Using pnpm
pnpm create vite my-react-app --template react

# Enter and install dependencies
cd my-react-app
npm install

# Start development server
npm run dev

Vite Project Structure:

my-react-app/
├── public/
│   └── vite.svg
├── src/
│   ├── App.jsx
│   ├── App.css
│   ├── main.jsx
│   ├── index.css
│   └── assets/
├── index.html
├── package.json
├── vite.config.js
└── README.md

Method 3: Next.js (Full-stack React Framework)

Creating a project:

bash
# Using create-next-app
npx create-next-app@latest my-next-app

# Select configuration options
Would you like to use TypeScript? No / Yes
Would you like to use ESLint? No / Yes
Would you like to use Tailwind CSS? No / Yes
Would you like to use `src/` directory? No / Yes
Would you like to use App Router? No / Yes
Would you like to customize the default import alias? No / Yes

# Start development server
cd my-next-app
npm run dev

Method 4: Manual Setup

Creating basic structure:

bash
# Create project directory
mkdir my-react-manual
cd my-react-manual

# Initialize package.json
npm init -y

# Install React dependencies
npm install react react-dom

# Install dev dependencies
npm install --save-dev @vitejs/plugin-react vite

Creating basic files:

index.html:

html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My React App</title>
</head>
<body>
    <div id="root"></div>
    <script type="module" src="/src/main.jsx"></script>
</body>
</html>

src/main.jsx:

jsx
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.jsx'
import './index.css'

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
)

src/App.jsx:

jsx
import { useState } from 'react'

function App() {
  const [count, setCount] = useState(0)

  return (
    <div>
      <h1>Hello React!</h1>
      <button onClick={() => setCount(count + 1)}>
        Click count: {count}
      </button>
    </div>
  )
}

export default App

vite.config.js:

javascript
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [react()],
})

🔧 Development Tool Configuration

VS Code Extensions Recommendations

Required Extensions:

json
{
  "recommendations": [
    "bradlc.vscode-tailwindcss",
    "esbenp.prettier-vscode",
    "ms-vscode.vscode-typescript-next",
    "formulahendry.auto-rename-tag",
    "christian-kohler.path-intellisense",
    "ms-vscode.vscode-json"
  ]
}

React-related Extensions:

  • ES7+ React/Redux/React-Native snippets: Code snippets
  • Bracket Pair Colorizer 2: Bracket pairing colorization
  • Auto Rename Tag: Auto rename tags
  • GitLens: Git enhancement
  • Thunder Client: API testing

Code Formatting Configuration

Prettier Configuration (.prettierrc):

json
{
  "semi": true,
  "trailingComma": "es5",
  "singleQuote": true,
  "printWidth": 80,
  "tabWidth": 2,
  "useTabs": false
}

ESLint Configuration (.eslintrc.js):

javascript
module.exports = {
  env: {
    browser: true,
    es2021: true,
    node: true,
  },
  extends: [
    'eslint:recommended',
    '@typescript-eslint/recommended',
    'plugin:react/recommended',
    'plugin:react-hooks/recommended',
  ],
  parser: '@typescript-eslint/parser',
  parserOptions: {
    ecmaFeatures: {
      jsx: true,
    },
    ecmaVersion: 12,
    sourceType: 'module',
  },
  plugins: ['react', '@typescript-eslint'],
  rules: {
    'react/react-in-jsx-scope': 'off',
  },
  settings: {
    react: {
      version: 'detect',
    },
  },
};

🌐 Browser Development Tools

React Developer Tools

Installing browser extensions:

Features:

jsx
// Add displayName to components for easier debugging
function MyComponent() {
  return <div>Hello</div>;
}
MyComponent.displayName = 'MyComponent';

// Using React DevTools Profiler
import { Profiler } from 'react';

function onRenderCallback(id, phase, actualDuration) {
  console.log('Component render info:', { id, phase, actualDuration });
}

function App() {
  return (
    <Profiler id="App" onRender={onRenderCallback}>
      <MyComponent />
    </Profiler>
  );
}

📦 Package Manager Comparison

npm vs yarn vs pnpm

npm (Default):

bash
# Install dependencies
npm install
npm install package-name
npm install --save-dev package-name

# Run scripts
npm run build
npm start

# Global install
npm install -g package-name

Yarn:

bash
# Install Yarn
npm install -g yarn

# Using Yarn
yarn install
yarn add package-name
yarn add --dev package-name

# Run scripts
yarn build
yarn start

pnpm (Recommended):

bash
# Install pnpm
npm install -g pnpm

# Using pnpm
pnpm install
pnpm add package-name
pnpm add -D package-name

# Run scripts
pnpm run build
pnpm start

Performance Comparison:

Featurenpmyarnpnpm
Install SpeedSlowFastFastest
Disk SpaceLargeLargeSmall
Offline SupportPartialGoodGood
SecurityGoodGoodGood

🛠️ Project Template Selection

Create React App Use Cases

Advantages:

  • Zero configuration to start
  • Good community support
  • Good for learning
  • Built-in testing environment

Disadvantages:

  • Slow build speed
  • Large bundle size
  • Less flexible configuration
bash
# Suitable for the following scenarios
npx create-react-app my-app           # Standard React app
npx create-react-app my-app --template typescript  # TypeScript project

Vite Use Cases

Advantages:

  • Extremely fast startup
  • Fast hot reload
  • Fast build speed
  • Flexible configuration

Disadvantages:

  • Relatively new
  • Smaller plugin ecosystem
bash
# Multiple template options
npm create vite@latest my-app -- --template react
npm create vite@latest my-app -- --template react-ts

Next.js Use Cases

Advantages:

  • Server-side rendering
  • Static site generation
  • API routes
  • File system routing

Use Cases:

  • SEO-important websites
  • Need server-side rendering
  • Full-stack application development
bash
npx create-next-app@latest my-next-app

🔍 Common Problem Solutions

Node.js Version Management

Using nvm (Recommended):

bash
# Install nvm
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash

# Using nvm
nvm install 18.17.0
nvm use 18.17.0
nvm alias default 18.17.0

# View installed versions
nvm list

Network Problem Solutions

Configuring npm registry:

bash
# Use Taobao mirror
npm config set registry https://registry.npmmirror.com

# Restore official registry
npm config set registry https://registry.npmjs.org

# View current registry
npm config get registry

Using cnpm:

bash
# Install cnpm
npm install -g cnpm --registry=https://registry.npmmirror.com

# Use cnpm instead of npm
cnpm install
cnpm install react

Permission Problem Solutions

Global package permission issues:

bash
# Create global directory
mkdir ~/.npm-global

# Configure npm
npm config set prefix '~/.npm-global'

# Add to environment variable (add to ~/.bashrc or ~/.zshrc)
export PATH=~/.npm-global/bin:$PATH

🎯 Verifying Installation

Creating a Test Project

bash
# Create test project
npx create-react-app test-installation
cd test-installation

# Start development server
npm start

Checking Key Features

jsx
// Modify src/App.js to test hot reload
import React, { useState } from 'react';
import './App.css';

function App() {
  const [message, setMessage] = useState('React installation successful!');

  return (
    <div className="App">
      <header className="App-header">
        <h1>{message}</h1>
        <button onClick={() => setMessage('Hot reload is working!')}>
          Test Hot Reload
        </button>
        <p>React version: {React.version}</p>
      </header>
    </div>
  );
}

export default App;

Performance Check

bash
# Check build
npm run build

# Check bundle size
npm install -g bundlephobia
bundlephobia analyze

# Run tests
npm test

📝 Chapter Summary

Through this chapter, you should have mastered:

Key Takeaways

  • ✅ Node.js and npm installation and configuration
  • ✅ Multiple React project creation methods
  • ✅ Development tools and extension configuration
  • ✅ Browser development tools usage
  • ✅ Package manager selection and usage
  • ✅ Common problem solutions

Best Practices

  1. Use LTS version of Node.js: Stable and reliable
  2. Choose appropriate project template: Based on requirements
  3. Configure code formatting tools: Maintain code consistency
  4. Install necessary development tools: Improve development efficiency
  5. Regularly update dependencies: Maintain security and performance

Next Steps

  • Learn project structure and file organization
  • Understand how development server works
  • Master build and deployment process

Continue Learning: Next Chapter - React Quick Start

Content is for learning and research only.