1. Introduction & use cases
React is a JavaScript library from Meta for building user interfaces out of small, reusable components. You describe what the screen should look like for the current data (state), and React updates the browser efficiently when the data changes.
A React app is usually a single-page application (SPA): the server sends one HTML file plus JavaScript bundles, and React renders every page in the browser. The modern way to start a plain React project is Vite – the old Create React App is deprecated. For server-side rendering and SEO-heavy sites, use a React framework such as Next.js.
Where it is used
- Dashboards, admin panels and internal tools
- Interactive front-ends for REST or GraphQL APIs
- E-commerce and booking interfaces
- Mobile apps with React Native (same component model)
2. Prerequisites
| You need | Version / notes |
|---|---|
| Node.js | Current LTS release (check with node -v). Download from nodejs.org or install with nvm. |
| npm | Comes with Node.js. (pnpm or Yarn also work.) |
| Code editor | VS Code with the ES7+ React snippets and ESLint extensions |
| Browser | Chrome, Edge or Firefox + the React Developer Tools extension |
| Basics | HTML, CSS and modern JavaScript (ES modules, arrow functions, async/await) |
3. Local setup
1Install Node.js
Install the LTS version from nodejs.org (Windows/macOS installer) or with nvm on macOS/Linux so you can switch versions later.
BASH# macOS / Linux with nvm curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/master/install.sh | bash nvm install --lts # check node -v npm -v2Create the project with Vite
Vite asks for a framework and variant – choose React and JavaScript (or TypeScript). The
--passes the template option through npm.BASHnpm create vite@latest my-react-app -- --template react # TypeScript instead: # npm create vite@latest my-react-app -- --template react-ts3Install dependencies and start the dev server
The dev server has hot reload: save a file and the browser updates instantly.
BASHcd my-react-app npm install npm run dev
4. Create & run a project
1Edit your first component
Open
src/App.jsxand replace it with a small counter. Components are functions that return JSX;useStatekeeps data that changes.src/App.jsximport { useState } from 'react'; export default function App() { const [count, setCount] = useState(0); return ( <main style={{ padding: 24 }}> <h1>Hello React</h1> <button onClick={() => setCount(count + 1)}>Clicked {count} times</button> </main> ); }2Fetch data from an API
Use
useEffectto load data when the component mounts. Read the API URL from an environment variable (see section 5).src/Users.jsximport { useEffect, useState } from 'react'; export function Users() { const [users, setUsers] = useState([]); useEffect(() => { fetch(`${import.meta.env.VITE_API_URL}/users`) .then((r) => r.json()) .then(setUsers) .catch(console.error); }, []); return <ul>{users.map((u) => <li key={u.id}>{u.name}</li>)}</ul>; }3Add pages with React Router
For several pages install React Router and wrap your routes.
JSXnpm install react-router // src/main.jsx import { BrowserRouter, Routes, Route } from 'react-router'; createRoot(document.getElementById('root')).render( <BrowserRouter> <Routes> <Route path="/" element={<App />} /> <Route path="/users" element={<Users />} /> </Routes> </BrowserRouter> );4Open it in the browser
Visit the URL Vite prints (usually
http://localhost:5173). Presso+ Enter in the terminal to open it.
✅ When it works you should see output like Figure 1.
5. Development configuration
Environment variables
Vite only exposes variables that start with VITE_ to browser code, read through import.meta.env. Everything in a React bundle is public – never put secret keys here. Use .env.production for build-time production values.
# .env (development)
VITE_API_URL=http://localhost:8000/api
VITE_APP_NAME=My React App
# .env.production (used by npm run build)
VITE_API_URL=https://api.example.com/apiKey dependencies
| Package / tool | Used for |
|---|---|
react, react-dom | The library and the browser renderer |
vite, @vitejs/plugin-react | Dev server with hot reload and production bundler |
react-router | Client-side routing between pages |
eslint | Finds bugs and enforces code style |
@tanstack/react-query (optional) | Caching and syncing server data |
vitest + @testing-library/react | Unit and component tests |
Folder structure
my-react-app/
├── public/ # copied as-is (favicon, robots.txt)
├── src/
│ ├── assets/ # images, fonts imported in code
│ ├── components/ # reusable UI pieces
│ ├── pages/ # route-level components
│ ├── App.jsx
│ └── main.jsx # entry: renders <App/>
├── index.html
├── .env
├── package.json
└── vite.config.jsEssential commands
| Command | What it does |
|---|---|
npm run dev | Start the dev server with hot reload |
npm run build | Create an optimised production build in dist/ |
npm run preview | Serve the production build locally to test it |
npm run lint | Run ESLint |
npm install <pkg> | Add a dependency |
6. Production deployment
A React (Vite) app compiles to static files – HTML, JS and CSS in dist/. Any static host can serve it: Nginx on a VPS (below), shared hosting, AWS S3 + CloudFront, Netlify or Vercel. No Node.js is needed on the server.
Server & hosting requirements
| Requirement | Recommendation |
|---|---|
| Server | Any static host; for a VPS 1 vCPU / 512 MB–1 GB RAM is plenty |
| Web server | Nginx or Apache with SPA fallback to index.html |
| Build machine | Node.js LTS (your PC or CI) to run npm run build |
| Domain + SSL | A/AAAA DNS records and a Let’s Encrypt certificate |
Deployment steps
1Build for production
Set production variables in
.env.production, then build. Test the result locally withnpm run preview.BASHnpm ci npm run build npm run preview # http://localhost:41732Prepare an Ubuntu server
Create a VPS (AWS EC2, DigitalOcean, Hostinger VPS, Linode …) with Ubuntu 24.04 LTS, at least 1 vCPU and 1–2 GB RAM. Log in with SSH, update the system and create a non-root user for the app.
BASHssh root@YOUR_SERVER_IP apt update && apt upgrade -y adduser deploy usermod -aG sudo deploy # copy your SSH key to the new user, then log in as deploy rsync --archive --chown=deploy:deploy ~/.ssh /home/deploy exit ssh deploy@YOUR_SERVER_IP3Upload the build
Copy the contents of
dist/to the web root on the server.BASH# on the server sudo mkdir -p /var/www/example.com sudo chown deploy:deploy /var/www/example.com # on your computer rsync -avz --delete dist/ deploy@YOUR_SERVER_IP:/var/www/example.com/4Serve the build with Nginx
Copy the build output to the server and let Nginx serve it. The
try_files … /index.htmlline sends every unknown path toindex.html, so client-side routes (React Router, Vue Router) work after a page refresh./etc/nginx/sites-available/example.comserver { listen 80; server_name example.com www.example.com; root /var/www/example.com; index index.html; location / { try_files $uri $uri/ /index.html; } location ~* \.(js|css|png|jpg|jpeg|gif|svg|webp|woff2?)$ { expires 30d; add_header Cache-Control "public, immutable"; } }5Enable the site and reload Nginx
Link the config into
sites-enabled, test it and reload.nginx -tmust say syntax is ok before you reload.BASHsudo apt install -y nginx sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/ sudo nginx -t sudo systemctl reload nginx6Open only the ports you need
Allow SSH, HTTP and HTTPS through the firewall. Application ports (3000, 8000 …) stay closed to the internet – Nginx forwards traffic to them.
BASHsudo ufw allow OpenSSH sudo ufw allow 'Nginx Full' # ports 80 and 443 (after installing Nginx) sudo ufw enable sudo ufw status7Point your domain to the server
In your domain registrar's DNS panel add an A record for
@(andwww) with the server's public IP address. DNS changes usually appear within minutes but can take up to 24–48 hours. Check withdigor an online DNS checker.OUTPUT# Type Name Value TTL # A @ 203.0.113.10 3600 # A www 203.0.113.10 3600 dig +short example.com8Add free HTTPS with Let’s Encrypt
Certbot gets a free SSL certificate, adds it to the Nginx config and redirects HTTP to HTTPS. Certificates renew automatically (a systemd timer runs twice a day); test renewal once with
--dry-run.BASHsudo apt install -y certbot python3-certbot-nginx sudo certbot --nginx -d example.com -d www.example.com sudo certbot renew --dry-run9Deploy updates
For each release build again and re-run
rsync. Vite adds content hashes to file names, so browsers download new files whileindex.htmlpoints to them.BASHnpm run build && rsync -avz --delete dist/ deploy@YOUR_SERVER_IP:/var/www/example.com/
🗺 The whole path from your code to the live site is drawn in the deployment diagram.
7. Images & screenshots
Illustrations drawn for this guide from the commands above. Product dashboards change often, so for screens such as cloud consoles follow the step text and the official documentation.
8. Common errors & solutions
404 Not Found when refreshing /users on the live site
The server looks for a real file called /users. Add the SPA fallback try_files $uri $uri/ /index.html; (Nginx) or a rewrite to index.html (Apache .htaccess).
import.meta.env.MY_VAR is undefined
Only variables prefixed with VITE_ are exposed. Rename to VITE_MY_VAR and restart npm run dev – env files are read at startup.
Blank page after deploy, console shows 404 for /assets/index-xxxx.js
The app is served from a sub-folder. Set base in vite.config.js, e.g. base: '/app/', and rebuild.
CORS error when calling the API
The API must send Access-Control-Allow-Origin for your site’s origin. In development you can use Vite’s proxy instead.
// vite.config.js
export default defineConfig({
plugins: [react()],
server: { proxy: { '/api': 'http://localhost:8000' } },
});Warning: Each child in a list should have a unique "key" prop
Give list items a stable unique key (an id from your data), not the array index when items can move.
npm ERR! ERESOLVE unable to resolve dependency tree
A package does not support your React version yet. Update the package, or as a last resort install with --legacy-peer-deps and test carefully.
Best practices
- Keep components small and pure; lift shared state up or use a store such as Redux only when needed.
- Never commit
.envfiles or keys – add them to.gitignore, keep a.env.examplewith dummy values, and store real secrets in the server or CI secret store. - Lazy-load heavy pages with
React.lazyandSuspenseto keep the first load small. - Run
npm run buildin CI on every pull request so broken builds never reach the server. - Use Next.js when pages must be indexed by search engines or need server rendering.