Frontend Components and React Basics
Build component based UIs with React, manage state, effects, and routing, and connect to Flask APIs.
Content
React project setup
Versions:
Watch & Learn
AI-discovered learning video
Sign in to watch the learning video for this topic.
React project setup — getting your frontend ready (CS50 Web Programming)
You already know how to fetch JSON, call APIs, and keep clients responsive. Now let’s make a project where that data lives and breathes — with components, routing, and a dev server that hot-reloads faster than your coffee cools.
Why this matters (quick refresher)
You’ve been doing Asynchronous JS, APIs, and JSON — so you can fetch data and build client-side routes. React project setup is the next step: creating the scaffolding where components, state, and routing come together. Think of it like building the stage before the play: you can fetch all the lines, but you need the set and lighting for the drama to work.
Goals for this guide
- Get a React dev environment up and running (fast).
- Understand the minimal file structure and key files.
- Wire in routing and API usage (you already know how to fetch!).
- Touch on PWA readiness, environment variables, linting, and deployment.
Pick your starter: Vite (recommended) or Create React App (CRA)
Both work. Vite is modern and lightning-fast; CRA is battle-tested and familiar for CS50 materials.
Commands (pick one):
- Vite (recommended):
npm create vite@latest my-app -- --template react
cd my-app
npm install
npm run dev
- Create React App (older default):
npx create-react-app my-app
cd my-app
npm start
Why Vite? Faster cold-starts, smaller config, and fewer mysterious Webpack messages at 2 AM.
Minimal project layout (what to expect)
my-app/
├─ index.html # base HTML shell
├─ package.json
├─ public/ # static files (favicons, assets)
├─ src/
│ ├─ main.jsx # app entry (index.js equivalent)
│ ├─ App.jsx # root React component
│ ├─ components/ # reusable UI parts
│ ├─ pages/ # route pages (Home, Profile, etc.)
│ ├─ styles/ # CSS or modules
│ └─ utils/ # fetch helpers, api clients
└─ .env # environment variables (optional)
Key files explained
- index.html: the single-page container. React will mount into a div here.
- main.jsx / index.js: initializes React and renders
into the DOM. - App.jsx: top-level component where you'll add routers, context providers, etc.
Quick sample: main.jsx + App.jsx + fetch example
main.jsx (Vite):
import React from 'react'
import { createRoot } from 'react-dom/client'
import App from './App'
import './styles/global.css'
createRoot(document.getElementById('root')).render(<App />)
App.jsx (simple router + fetch example):
import React from 'react'
import { BrowserRouter, Routes, Route, Link } from 'react-router-dom'
import Home from './pages/Home'
import Profile from './pages/Profile'
export default function App(){
return (
<BrowserRouter>
<nav>
<Link to="/">Home</Link> | <Link to="/profile">Profile</Link>
</nav>
<Routes>
<Route path="/" element={<Home/>} />
<Route path="/profile" element={<Profile/>} />
</Routes>
</BrowserRouter>
)
}
Home.jsx (using fetch + useEffect):
import React, { useEffect, useState } from 'react'
export default function Home(){
const [data, setData] = useState(null)
useEffect(() => {
fetch('/api/messages')
.then(r => r.json())
.then(setData)
.catch(err => console.error('Fetch error', err))
}, [])
return <div>{data ? <pre>{JSON.stringify(data, null, 2)}</pre> : 'Loading...'}</div>
}
This connects everything: React components, client-side routing (you learned the basics earlier), and a fetch call to your API.
Environment variables & API keys
- CRA: prefix variables with REACT_APP_ in .env (e.g., REACT_APP_API_URL).
- Vite: prefix with VITE_ (e.g., VITE_API_URL).
Never store secrets in client-side env files — they are visible in the browser. Use them for base URLs and non-secret flags.
Dev tooling that makes life nicer
- React DevTools (browser extension) — inspect component props/state.
- ESLint + Prettier — consistent style and fewer bugs.
- TypeScript (optional) — safer props and state.
- Testing Library + Jest — write tests for components.
Install examples:
npm install react-router-dom
npm install -D eslint prettier
Progressive Web App (PWA) readiness
You already saw PWA concepts earlier. CRA can register a service worker with a flag; Vite needs plugins. If you want offline caching for API responses, consider a service worker strategy that caches static assets and optionally caches API results (careful with stale data — design cache invalidation).
Deploying your React app
Build and push to a static host:
npm run build
# deploy the ./dist (Vite) or ./build (CRA) folder to Netlify / Vercel / GitHub Pages
Netlify / Vercel auto-detects React apps from your repo and runs the build for you. They also give previews — tiny miracles for demos.
Common pitfalls & quick fixes
- Blank page on refresh? If using client-side routing, configure your host to serve index.html for all routes.
- CORS when calling an API: enable CORS on the server or use a proxy during development (Vite/CRA can proxy API calls).
- Environment variable not available: check prefix (REACT_APP_ vs VITE_). Restart dev server after editing .env.
"You can write perfect fetch logic, but without the right client structure you'll be debugging file paths at 1 AM." — Your future calm self.
Key takeaways
- Choose Vite for speed; CRA still works for tradition or course parity.
- Keep a clear structure: src/, components/, pages/, utils/.
- Wire routing with react-router-dom and fetch data inside components (useEffect), building on what you already know about asynchronous JS.
- Use env prefixes correctly, set up linting, and think about PWA/service worker later — not in the first 15 minutes.
Final, actually-memorable insight
Treat your React project like a play: the API is the script, components are the actors, the router is the stage manager, and the build tool is the lighting crew. If your stage is organized, the show (and your debugging life) will be dramatically better.
Happy building — and when your app finally hot-reloads, take a tiny victory lap.
Comments (0)
Please sign in to leave a comment.
No comments yet. Be the first to comment!