React Web App Development - Detailed Concepts
with Examples
This guide breaks down all the key concepts in React for web app development, with explanations and
code examples.
Fundamentals
1. JSX (JavaScript XML)
JSX allows writing HTML-like code in JavaScript.
const element = <h1>Hello, world!</h1>;
JSX is syntactic sugar for:
const element = React.createElement('h1', null, 'Hello, world!');
2. Components
React applications are built using components.
Functional Component:
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
Usage:
<Welcome name="Alice" />
3. Props (Properties)
Props are read-only attributes passed to components.
1
function Greeting(props) {
return <p>Welcome, {props.user}</p>;
}
4. State
State allows components to manage dynamic data.
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
5. Event Handling
function Button() {
function handleClick() {
alert('Button clicked!');
}
return <button onClick={handleClick}>Click Me</button>;
}
6. Conditional Rendering
function LoginStatus({ isLoggedIn }) {
return isLoggedIn ? <p>Welcome back!</p> : <p>Please log in.</p>;
}
7. Lists and Keys
function ItemList() {
const items = ['Apple', 'Banana', 'Orange'];
return (
<ul>
{items.map((item, index) => (
2
<li key={index}>{item}</li>
))}
</ul>
);
}
8. useEffect Hook
import { useEffect, useState } from 'react';
function Timer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const interval = setInterval(() => setSeconds((s) => s + 1), 1000);
return () => clearInterval(interval);
}, []);
return <p>Seconds: {seconds}</p>;
}
Intermediate Concepts
1. Forms and Input Handling
function NameForm() {
const [name, setName] = useState('');
const handleChange = (e) => setName(e.target.value);
const handleSubmit = (e) => {
e.preventDefault();
alert(`Hello, ${name}`);
};
return (
<form onSubmit={handleSubmit}>
<input type="text" value={name} onChange={handleChange} />
<button type="submit">Submit</button>
</form>
);
}
2. Component Lifecycle via Hooks
useEffect mimics lifecycle methods.
3
useEffect(() => {
console.log("Component mounted");
return () => console.log("Component unmounted");
}, []);
3. Context API
const ThemeContext = React.createContext('light');
function ThemedButton() {
const theme = useContext(ThemeContext);
return <button style={{ background: theme === 'dark' ? '#333' : '#FFF' }}
>Click</button>;
}
function App() {
return (
<ThemeContext.Provider value="dark">
<ThemedButton />
</ThemeContext.Provider>
);
}
4. React Router
import { BrowserRouter, Route, Routes, Link } from 'react-router-dom';
function Home() {
return <h2>Home</h2>;
}
function About() {
return <h2>About</h2>;
}
function App() {
return (
<BrowserRouter>
<nav>
<Link to="/">Home</Link> | <Link to="/about">About</Link>
</nav>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</BrowserRouter>
);
}
4
5. Lifting State Up
function Parent() {
const [value, setValue] = useState('');
return (
<div>
<Input value={value} onChange={setValue} />
<Display value={value} />
</div>
);
}
function Input({ value, onChange }) {
return <input value={value} onChange={(e) => onChange(e.target.value)} />;
}
function Display({ value }) {
return <p>{value}</p>;
}
6. Custom Hooks
function useCounter(initialValue = 0) {
const [count, setCount] = useState(initialValue);
const increment = () => setCount(count + 1);
return [count, increment];
}
function Counter() {
const [count, increment] = useCounter();
return <button onClick={increment}>Count: {count}</button>;
}
Advanced Concepts
1. React Query
import { useQuery } from '@tanstack/react-query';
function Users() {
const { data, isLoading } = useQuery(['users'], () => fetch('/api/
users').then(res => res.json()));
if (isLoading) return <p>Loading...</p>;
return (
<ul>{data.map(user => <li key={user.id}>{user.name}</li>)}</ul>
5
);
}
2. Performance Optimization
const ExpensiveComponent = React.memo(function ({ data }) {
return <div>{data}</div>;
});
3. Code Splitting and Lazy Loading
import React, { Suspense, lazy } from 'react';
const LazyComponent = lazy(() => import('./LazyComponent'));
function App() {
return (
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
);
}
4. Error Boundaries
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError() {
return { hasError: true };
}
render() {
if (this.state.hasError) return <h1>Something went wrong.</h1>;
return this.props.children;
}
}
5. Testing
Using React Testing Library:
import { render, screen } from '@testing-library/react';
import App from './App';
6
test('renders welcome message', () => {
render(<App />);
expect(screen.getByText(/welcome/i)).toBeInTheDocument();
});
6. TypeScript with React
interface UserProps {
name: string;
}
const User: React.FC<UserProps> = ({ name }) => <p>Hello, {name}</p>;
7. State Management Libraries (Redux Example)
// store.js
import { configureStore, createSlice } from '@reduxjs/toolkit';
const counterSlice = createSlice({
name: 'counter',
initialState: 0,
reducers: {
increment: state => state + 1,
},
});
export const { increment } = counterSlice.actions;
export const store = configureStore({ reducer: counterSlice.reducer });
8. Styling
// With Tailwind CSS
<button className="bg-blue-500 text-white px-4 py-2 rounded">Click</button>
Let me know if you want project ideas or an interactive learning roadmap next!