Prerequisites: Installing Node.js and npm
Before you can start building React applications, you need to set up your development environment. The first essential tool is Node.js, which includes npm (Node Package Manager).
Why Node.js for React? While React runs in the browser, we use Node.js during development for running build tools, package managers, and development servers. You're not building a backend server - Node.js is just the tooling environment.
Installing Node.js:
- Visit
nodejs.org
- Download the LTS (Long Term Support) version
- Run the installer and follow the prompts
- Verify installation by opening a terminal and running:
# Check Node.js version
node --version
# Should output something like: v18.17.0
# Check npm version
npm --version
# Should output something like: 9.6.7
Version Recommendation: Use Node.js version 16.x or higher. The LTS version is recommended for stability. React works with older Node versions, but newer versions provide better performance and security.
Method 1: Create React App (CRA)
Create React App is the official tool for setting up new React projects. It handles all the complex configuration (Webpack, Babel, ESLint) so you can focus on coding.
Creating Your First React App:
# Create a new React application
npx create-react-app my-first-app
# Navigate into the project directory
cd my-first-app
# Start the development server
npm start
What is npx? npx comes with npm 5.2+ and allows you to run packages without installing them globally. It downloads the latest version of create-react-app, uses it to create your project, then removes it.
What Happens When You Run These Commands:
- Creates a new folder with your project name
- Installs React, ReactDOM, and development dependencies
- Sets up the project structure with sensible defaults
- Configures build tools (Webpack, Babel) behind the scenes
- Creates a basic starter application
- Initializes a Git repository
After running npm start, your default browser will open to http://localhost:3000 and you'll see the spinning React logo!
Hot Module Replacement: The development server includes hot reloading. When you save changes to your code, the browser automatically updates without a full page refresh, preserving application state. This makes development much faster!
Method 2: Vite (Modern Alternative)
Vite is a newer, blazingly fast build tool that has become very popular in the React community. It provides instant server start and lightning-fast hot module replacement.
Creating a React App with Vite:
# Create a new Vite project
npm create vite@latest my-vite-app
# You'll be prompted to:
# 1. Select a framework → Choose "React"
# 2. Select a variant → Choose "JavaScript" (or TypeScript)
# Navigate into the project
cd my-vite-app
# Install dependencies
npm install
# Start the development server
npm run dev
Vite vs Create React App:
Create React App (CRA):
✓ Official React tool, well-established
✓ Zero configuration, everything pre-configured
✓ Large ecosystem and community support
✓ Better for beginners (more tutorials use it)
✗ Slower build times as projects grow
✗ More opinionated, harder to customize
Vite:
✓ Extremely fast development server (instant start)
✓ Lightning-fast hot module replacement
✓ Smaller production bundles
✓ More flexible and easier to configure
✓ Modern tooling with better DX (Developer Experience)
✗ Newer tool, slightly smaller community
✗ Some older tutorials don't cover it
Which Should You Choose? For learning React, either tool works great! This tutorial uses Create React App because it's more commonly used in tutorials and has zero configuration. However, for production projects, many developers now prefer Vite for its speed.
Understanding the Project Structure
Let's explore the files and folders that Create React App generates:
my-first-app/
├── node_modules/ # All installed dependencies (don't edit)
├── public/ # Static files
│ ├── index.html # Main HTML file
│ ├── favicon.ico # Browser tab icon
│ ├── manifest.json # PWA configuration
│ └── robots.txt # Search engine instructions
├── src/ # Your React code lives here
│ ├── App.css # Styles for App component
│ ├── App.js # Main App component
│ ├── App.test.js # Tests for App component
│ ├── index.css # Global styles
│ ├── index.js # Entry point of the app
│ ├── logo.svg # React logo image
│ └── reportWebVitals.js # Performance monitoring
├── .gitignore # Files Git should ignore
├── package.json # Project dependencies and scripts
├── package-lock.json # Locked dependency versions
└── README.md # Project documentation
Key Files Explained:
1. public/index.html - The single HTML file for your entire app:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>React App</title>
</head>
<body>
<!-- This is where React mounts your app -->
<div id="root"></div>
</body>
</html>
2. src/index.js - The JavaScript entry point:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
// Create a root and render the App component
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
React.StrictMode: This is a development tool that activates additional checks and warnings for your components. It doesn't render any visible UI and doesn't affect production builds. It helps you write better React code by catching potential problems early.
3. src/App.js - Your main component:
import logo from './logo.svg';
import './App.css';
function App() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
</header>
</div>
);
}
export default App;
4. package.json - Project configuration:
{
"name": "my-first-app",
"version": "0.1.0",
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1"
},
"scripts": {
"start": "react-scripts start", // Development server
"build": "react-scripts build", // Production build
"test": "react-scripts test", // Run tests
"eject": "react-scripts eject" // Advanced: expose config
}
}
Don't Eject Unless Necessary: The eject command exposes all the hidden configuration files. This is a one-way operation - you can't undo it! Only eject if you absolutely need to customize the build configuration. For 99% of projects, you won't need to eject.
Available npm Scripts
Create React App provides several useful commands:
npm start
- Starts the development server on http://localhost:3000
- Enables hot reloading (auto-refresh on save)
- Shows lint errors in the console
- Opens your default browser automatically
npm run build
- Creates an optimized production build
- Minifies JavaScript and CSS
- Generates static files in the build/ folder
- Ready to deploy to any static hosting service
npm test
- Runs the test suite in interactive watch mode
- Re-runs tests when you save files
- Uses Jest testing framework
npm run eject
- One-way operation: exposes all configuration
- Gives you full control over Webpack, Babel, ESLint
- Use only if absolutely necessary
Your First Code Change
Let's make your first modification to see React in action:
// Open src/App.js and replace the entire content with:
import './App.css';
function App() {
return (
<div className="App">
<header className="App-header">
<h1>Hello, React!</h1>
<p>This is my first React application.</p>
<p>The current time is: {new Date().toLocaleTimeString()}</p>
</header>
</div>
);
}
export default App;
Save the file, and watch your browser automatically update! The page should now display your custom message with the current time.
Notice the Curly Braces: The {new Date().toLocaleTimeString()} syntax allows you to embed JavaScript expressions inside your JSX. This is one of React's most powerful features - you can dynamically generate content using JavaScript. We'll explore this in detail in the next lesson!
Introduction to JSX
In the code above, you're writing JSX (JavaScript XML). JSX looks like HTML but has the full power of JavaScript:
// This JSX code...
const element = <h1>Hello, {name}!</h1>;
// ...is transformed by Babel into this JavaScript:
const element = React.createElement(
'h1',
null,
'Hello, ',
name,
'!'
);
JSX Key Differences from HTML:
- Use
className instead of class (because "class" is a reserved JavaScript keyword)
- Use
htmlFor instead of for in labels
- All tags must be closed:
<img /> not <img>
- camelCase for event handlers:
onClick not onclick
- Style attribute accepts objects:
style={{color: 'red'}}
JSX is Optional: You don't have to use JSX with React. You could use plain React.createElement() calls instead. However, JSX makes React code much more readable and is used by 99% of React developers. We'll deep dive into JSX in the next lesson.
Development Tools
Install these browser extensions to enhance your React development experience:
1. React Developer Tools
Chrome: Search "React Developer Tools" in Chrome Web Store
Firefox: Search "React Developer Tools" in Firefox Add-ons
Features:
- Inspect React component hierarchy
- View component props and state
- Track component updates and performance
- Edit props and state in real-time
- Identify which components re-render
2. Redux DevTools (for later when you learn state management)
Using React DevTools:
- Open your React app in the browser
- Open browser DevTools (F12 or Right-click → Inspect)
- Click the "Components" tab (added by React DevTools)
- You'll see your component tree starting with
<App>
- Click any component to see its props and state
Profiler Tab: React DevTools also includes a "Profiler" tab for measuring component performance. This is invaluable when optimizing React applications. We'll cover performance optimization in later lessons.
Code Editor Setup
While you can use any text editor, Visual Studio Code (VS Code) is the most popular choice for React development:
Recommended VS Code Extensions:
1. ES7+ React/Redux/React-Native snippets
- Type shortcuts like "rfce" to generate component boilerplate
2. Prettier - Code formatter
- Auto-formats your code on save
- Ensures consistent code style
3. ESLint
- Catches common JavaScript errors
- Enforces code quality standards
4. Auto Rename Tag
- Automatically renames closing JSX tags
5. Bracket Pair Colorizer
- Color-codes matching brackets for easier reading
6. Path Intellisense
- Autocompletes file paths in imports
VS Code Settings for React:
// Add to your VS Code settings.json:
{
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"emmet.includeLanguages": {
"javascript": "javascriptreact"
},
"emmet.triggerExpansionOnTab": true
}
Troubleshooting Common Setup Issues
Issue 1: "npm is not recognized"
Solution: Node.js wasn't installed correctly or isn't in your PATH. Reinstall Node.js and restart your terminal.
Issue 2: Port 3000 already in use
Solution: Another application is using port 3000. Either close that app or start React on a different port:
PORT=3001 npm start (Mac/Linux)
set PORT=3001 && npm start (Windows)
Issue 3: "Module not found" errors
Solution: Delete node_modules folder and package-lock.json, then run npm install again.
Issue 4: Changes not appearing in browser
Solution: Clear browser cache (Ctrl+Shift+R), or stop the dev server and restart with npm start.
Exercise 1: Create Your First React App
- Open your terminal/command prompt
- Navigate to a folder where you want to create your project
- Run:
npx create-react-app my-react-journey
- Wait for installation to complete (may take 2-5 minutes)
- Navigate into the folder:
cd my-react-journey
- Start the development server:
npm start
- Verify the app opens in your browser at localhost:3000
Exercise 2: Customize the Default App
Modify src/App.js to create a personal welcome page:
- Change the heading to include your name
- Add a paragraph describing why you're learning React
- Display the current date using:
{new Date().toLocaleDateString()}
- Add at least 3 list items with your learning goals
Save the file and observe the automatic browser update!
Exercise 3: Install React DevTools
- Open Chrome or Firefox
- Search for "React Developer Tools" in your browser's extension store
- Install the extension
- Open your React app and press F12
- Find the "Components" tab in DevTools
- Click on the
<App> component to inspect it
- Explore the component tree and properties
Summary
In this lesson, you learned how to:
- Install Node.js and npm, the prerequisites for React development
- Create a React application using Create React App or Vite
- Understand the project structure and key files
- Use npm scripts to start development server and build for production
- Make your first code changes and see hot reloading in action
- Install and use React Developer Tools for debugging
- Set up VS Code with helpful extensions for React development
- Troubleshoot common setup issues
You now have a fully functional React development environment! In the next lesson, we'll dive deep into JSX syntax and learn how to write dynamic, expressive React components.