React Router & State Management
613 words
3 min read
Visual companion
Python
Type and operator map
Python Week 1: the first filter for runtime behavior
View
Revision summary
What this note is really saying
Short form
# React Router & State Management ## 🎯 Learning Objectives - Set up React Router for multi-page SPA - Create navigable routes with parameters - Use Context API for global state - Understand Redux concepts ## 1. React Router — Client-Side Routing Single Page Applications (SPAs) handle routing in the browser without...

React Router & State Management
🎯 Learning Objectives
- Set up React Router for multi-page SPA
- Create navigable routes with parameters
- Use Context API for global state
- Understand Redux concepts
1. React Router — Client-Side Routing
Single Page Applications (SPAs) handle routing in the browser without server requests.
jsx// npm install react-router-dom import { BrowserRouter, Routes, Route, Link, useParams, useNavigate } from 'react-router-dom'; function App() { return ( <BrowserRouter> <nav> <Link to="/">Home</Link> <Link to="/about">About</Link> <Link to="/users">Users</Link> </nav> <Routes> <Route path="/" element={<Home />} /> <Route path="/about" element={<About />} /> <Route path="/users" element={<Users />} /> <Route path="/users/:id" element={<UserDetail />} /> <Route path="*" element={<NotFound />} /> </Routes> </BrowserRouter> ); } // Route with parameter function UserDetail() { const { id } = useParams(); const navigate = useNavigate(); return ( <div> <h1>User {id}</h1> <button onClick={() => navigate('/users')}>Back</button> </div> ); }
2. Context API — Global State
jsx// Create context const AuthContext = React.createContext(null); // Provider component function AuthProvider({ children }) { const [user, setUser] = React.useState(null); const login = (username, password) => { // Authenticate, set user setUser({ name: username }); }; const logout = () => { setUser(null); }; return ( <AuthContext.Provider value={{ user, login, logout }}> {children} </AuthContext.Provider> ); } // Usage in any component function Profile() { const { user, logout } = React.useContext(AuthContext); if (!user) return <Navigate to="/login" />; return ( <div> <p>Welcome, {user.name}!</p> <button onClick={logout}>Logout</button> </div> ); } // Wrap app with provider <AuthProvider> <App /> </AuthProvider>
3. Practice Questions
Q1: What is React Router used for?Answer: Enables client-side routing in SPAs. Changes the URL and renders different components without a page reload. Supports nested routes, URL parameters, programmatic navigation, and lazy loading. Q2: How do you get URL parameters in React Router?Answer: UseuseParams()hook. For route/users/:id,const { id } = useParams()gives the value from the URL. Q3: What is the difference between Context API and Redux?Answer: Context API is built into React, simple, good for small/medium apps (theme, auth). Redux has a larger ecosystem, middleware (thunks, sagas), devtools, and is better for complex state logic across large apps. Use Context API first; add Redux when you need it. Q4: How do you programmatically navigate in React Router?Answer: Use theuseNavigate()hook.const navigate = useNavigate();thennavigate('/path')ornavigate(-1)(go back). Previously useduseHistory(). Q5: What does `` do?Answer: A declarative navigation component (replaces the oldRedirectcomponent). When rendered, it navigates to the specified route. Commonly used for protected routes:if (!user) return <Navigate to="/login" />;. Q6: How do you create a "not found" route?Answer:<Route path="*" element={<NotFound />} />— the wildcard*matches any path. Place it as the last route to catch all unmatched URLs. Q7: What is prop drilling and how does Context solve it?Answer: Prop drilling is passing data through multiple component levels. Context provides a way to share values directly from a Provider to any nested Consumer without intermediate props. Q8: How do you create a protected route?jsxfunction ProtectedRoute({ children }) { const { user } = React.useContext(AuthContext); if (!user) return <Navigate to="/login" />; return children; } // Usage: <Route path="/dashboard" element={ <ProtectedRoute><Dashboard /></ProtectedRoute> } />
📐 Key Concepts
| Feature | Component/Hook | Purpose |
|---|---|---|
| Router | `` | Wrap app for routing |
| Routes | `` | Define routes |
| Link | `` | Navigation link |
| Params | useParams() | Get URL parameters |
| Navigate | useNavigate() | Programmatic navigation |
| Context | createContext() / useContext() | Global state |
| Provider | `` | Provide state to children |