Building and Deploying React Applications

Learn to build, optimize, and deploy your React applications to production.

Understanding the Build Process: From Development to Production

The build process transforms your development code into optimized production-ready files that browsers can understand and load efficiently.

Build Process Steps

  1. Code Transformation: JSX → JavaScript, TypeScript → JavaScript
  2. Module Bundling: Combining files into optimized bundles
  3. Asset Optimization: Minifying CSS/JS, optimizing images
  4. Dead Code Elimination: Removing unused code

Why Building Matters

  • Performance: Smaller files load faster
  • Compatibility: Works in all browsers
  • Security: Removes development-only code
  • Optimization: Better caching and loading strategies

Popular Build Tools

  • Create React App: Built-in webpack configuration
  • Vite: Fast build tool with instant updates
  • Next.js: Full-stack React framework
1// Basic build setup
2{
3 "scripts": {
4 "build": "react-scripts build",
5 "start": "react-scripts start"
6 }
7}
8
9// Build your app
10npm run build
11
12// Environment variables
13// .env
14REACT_APP_API_URL=https://api.myapp.com
15
16// Using environment variables
17function App() {
18 const apiUrl = process.env.REACT_APP_API_URL;
19
20 return (
21 <div>
22 <h1>My App</h1>
23 <p>API: {apiUrl}</p>
24 </div>
25 );
26}
27
28// Code splitting for better performance
29import { lazy, Suspense } from 'react';
30
31const Dashboard = lazy(() => import('./Dashboard'));
32
33function App() {
34 return (
35 <Suspense fallback={<div>Loading...</div>}>
36 <Dashboard />
37 </Suspense>
38 );
39}
40
41// Tree shaking - import only what you need
42import debounce from 'lodash/debounce';
43const result = debounce(myFunction, 300);

Deployment Options: Getting Your App Online

Deployment makes your React application available on the internet. Choose a platform that fits your needs and budget.

Popular Deployment Platforms

Vercel

  • Best for: Next.js apps and static sites
  • Features: Automatic deployments, preview URLs
  • Free tier: Generous limits

Netlify

  • Best for: Static sites with forms
  • Features: Drag-and-drop deploy, serverless functions
  • Free tier: 100GB bandwidth/month

GitHub Pages

  • Best for: Open source projects, portfolios
  • Features: Free for public repos, Git integration
  • Limitations: Static sites only

Deployment Steps

  1. Build your app: npm run build
  2. Upload build files to hosting service
  3. Configure domain (optional)
  4. Set up continuous deployment

Continuous Deployment Automatically deploy when you push code:

  • Connect GitHub repository
  • Push to main branch → automatic deployment
  • Preview URLs for pull requests
1// Netlify deployment
2// netlify.toml
3[build]
4 command = "npm run build"
5 publish = "build"
6
7[[redirects]]
8 from = "/*"
9 to = "/index.html"
10 status = 200
11
12// Deploy with CLI
13npm install -g netlify-cli
14netlify deploy --prod
15
16// Vercel deployment
17// vercel.json
18{
19 "builds": [{ "src": "package.json", "use": "@vercel/static-build" }],
20 "routes": [{ "src": "/(.*)", "dest": "/index.html" }]
21}
22
23// Deploy with CLI
24npm install -g vercel
25vercel
26
27// GitHub Pages deployment
28// package.json
29{
30 "homepage": "https://yourusername.github.io/your-repo-name",
31 "scripts": {
32 "predeploy": "npm run build",
33 "deploy": "gh-pages -d build"
34 }
35}
36
37npm install --save-dev gh-pages
38npm run deploy

Performance Optimization: Making Your App Lightning Fast

Performance optimization improves user experience and SEO. Focus on loading speed, interactivity, and visual stability.

Core Web Vitals Google's user experience metrics:

  • LCP: Loading performance
  • FID: Interactivity
  • CLS: Visual stability

Key Optimization Strategies

Bundle Optimization

  • Remove unused dependencies
  • Use production builds
  • Implement code splitting
  • Tree shake imports

Asset Optimization

  • Compress images (WebP format)
  • Lazy load images
  • Use appropriate image sizes

Runtime Performance

  • Memoize expensive calculations
  • Use React.memo wisely
  • Debounce/throttle events

Measuring Performance

  • Chrome DevTools
  • Lighthouse audits
  • React DevTools Profiler
1// Lazy loading routes
2import { lazy, Suspense } from 'react';
3import { BrowserRouter, Routes, Route } from 'react-router-dom';
4
5const Home = lazy(() => import('./pages/Home'));
6const Dashboard = lazy(() => import('./pages/Dashboard'));
7
8function App() {
9 return (
10 <BrowserRouter>
11 <Suspense fallback={<div>Loading...</div>}>
12 <Routes>
13 <Route path="/" element={<Home />} />
14 <Route path="/dashboard" element={<Dashboard />} />
15 </Routes>
16 </Suspense>
17 </BrowserRouter>
18 );
19}
20
21// Optimize with React.memo and useMemo
22import { memo, useMemo, useCallback } from 'react';
23
24const ExpensiveList = memo(function ExpensiveList({ items, onItemClick }) {
25 const sortedItems = useMemo(() => {
26 return [...items].sort((a, b) => b.priority - a.priority);
27 }, [items]);
28
29 return (
30 <ul>
31 {sortedItems.map(item => (
32 <li key={item.id} onClick={() => onItemClick(item.id)}>
33 {item.name} (Priority: {item.priority})
34 </li>
35 ))}
36 </ul>
37 );
38});
39
40function TodoApp() {
41 const [todos, setTodos] = useState([
42 { id: 1, name: 'Learn React', priority: 3 },
43 { id: 2, name: 'Build App', priority: 2 }
44 ]);
45
46 const handleItemClick = useCallback((id) => {
47 console.log('Item clicked:', id);
48 }, []);
49
50 return (
51 <div>
52 <ExpensiveList items={todos} onItemClick={handleItemClick} />
53 </div>
54 );
55}
56
57// Image lazy loading
58function LazyImage({ src, alt }) {
59 return (
60 <img
61 src={src}
62 alt={alt}
63 loading="lazy"
64 style={{ width: '100%', height: 'auto' }}
65 />
66 );
67}

Production Best Practices: Building Apps That Last

Production deployment requires security, maintainability, and excellent user experience. Follow these best practices for production-ready React applications.

Security Best Practices

  • Never expose API keys in frontend code
  • Implement Content Security Policy (CSP)
  • Use HTTPS everywhere
  • Sanitize user inputs
  • Keep dependencies updated

Error Handling & Monitoring

  • Error boundaries for graceful failures
  • Error tracking (Sentry, LogRocket)
  • Performance monitoring
  • Uptime monitoring

SEO & Accessibility

  • Meta tags and Open Graph
  • Proper heading hierarchy
  • Alt text for images
  • Semantic HTML

Maintenance & Updates

  • Automated testing
  • Continuous integration
  • Dependency updates
  • Regular security audits
1// Environment variables security
2// ✅ Use environment variables for configuration
3const API_URL = process.env.REACT_APP_API_URL;
4// Keep secrets on the backend!
5
6// Content Security Policy
7// public/index.html
8<meta
9 http-equiv="Content-Security-Policy"
10 content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline';"
11/>
12
13// Input sanitization
14import DOMPurify from 'dompurify';
15
16function SafeHTML({ html }) {
17 const sanitized = DOMPurify.sanitize(html, {
18 ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'a'],
19 ALLOWED_ATTR: ['href']
20 });
21
22 return <div dangerouslySetInnerHTML={{ __html: sanitized }} />;
23}
24
25// Error boundary
26class ErrorBoundary extends React.Component {
27 constructor(props) {
28 super(props);
29 this.state = { hasError: false };
30 }
31
32 static getDerivedStateFromError(error) {
33 return { hasError: true };
34 }
35
36 componentDidCatch(error, errorInfo) {
37 console.error('Error caught:', error);
38 }
39
40 render() {
41 if (this.state.hasError) {
42 return (
43 <div className="error-fallback">
44 <h2>Something went wrong</h2>
45 <button onClick={() => window.location.reload()}>
46 Refresh Page
47 </button>
48 </div>
49 );
50 }
51
52 return this.props.children;
53 }
54}
55
56// SEO with React Helmet
57import { Helmet } from 'react-helmet';
58
59function ProductPage({ product }) {
60 return (
61 <>
62 <Helmet>
63 <title>{product.name} | My Store</title>
64 <meta name="description" content={product.description} />
65 <meta property="og:title" content={product.name} />
66 <meta property="og:description" content={product.description} />
67 </Helmet>
68
69 <article>
70 <h1>{product.name}</h1>
71 <img src={product.image} alt={product.name} />
72 <p>{product.description}</p>
73 </article>
74 </>
75 );
76}