markdown
Copy
# Understanding React: Key Concepts with Uses & Code Examples
---
## 1. Component-Based Architecture
**Use**: Build reusable UI elements.
```jsx
// Functional Component
function Button(props) {
return <button onClick={props.onClick}>{props.label}</button>;
}
// Usage
<Button label="Click Me" onClick={() => console.log("Clicked!")} />
2. JSX (JavaScript XML)
Use: Write HTML-like syntax in JavaScript.
jsx
Copy
const element = <h1 className="title">Hello, React!</h1>;
3. State Management with useState
Use: Track dynamic data in functional components.
jsx
Copy
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>
);
}
4. Props
Use: Pass data from parent to child components.
jsx
Copy
function UserCard({ name, age }) {
return (
<div>
<h2>{name}</h2>
<p>Age: {age}</p>
</div>
);
}
// Usage
<UserCard name="John Doe" age={30} />
5. useEffect Hook
Use: Handle side effects (e.g., API calls).
jsx
Copy
import { useState, useEffect } from 'react';
function DataFetcher() {
const [data, setData] = useState(null);
useEffect(() => {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => setData(data));
}, []); // Empty dependency array = runs once on mount
return <div>{data ? data.message : 'Loading...'}</div>;
}
6. Conditional Rendering
Use: Show/hide elements based on conditions.
jsx
Copy
function Greeting({ isLoggedIn }) {
return (
<div>
{isLoggedIn ? <h1>Welcome Back!</h1> : <h1>Please Sign In</h1>}
</div>
);
}
7. List Rendering with Keys
Use: Render dynamic lists efficiently.
jsx
Copy
function TodoList({ todos }) {
return (
<ul>
{todos.map(todo => (
<li key={todo.id}>{todo.text}</li>
))}
</ul>
);
}
8. Context API
Use: Share global state without prop drilling.
jsx
Copy
import { createContext, useContext } from 'react';
const ThemeContext = createContext('light');
function App() {
return (
<ThemeContext.Provider value="dark">
<Toolbar />
</ThemeContext.Provider>
);
}
function Toolbar() {
const theme = useContext(ThemeContext);
return <div>Current Theme: {theme}</div>;
}
9. React Router
Use: Handle client-side navigation.
jsx
Copy
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
function App() {
return (
<Router>
<Link to="/about">About</Link>
<Route path="/about" component={AboutPage} />
</Router>
);
}
10. Forms (Controlled Components)
Use: Manage form data with React state.
jsx
Copy
function LoginForm() {
const [email, setEmail] = useState('');
const handleSubmit = (e) => {
e.preventDefault();
console.log('Email:', email);
};
return (
<form onSubmit={handleSubmit}>
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
<button type="submit">Submit</button>
</form>
);
}
11. Performance Optimization (React.memo, useMemo)
Use: Avoid unnecessary re-renders.
jsx
Copy
const MemoizedComponent = React.memo(function ExpensiveComponent({ value }) {
// Renders only when `value` changes
return <div>{value}</div>;
});
// Usage
<MemoizedComponent value={someValue} />
12. Styling with CSS Modules
Use: Scope CSS to components.
jsx
Copy
// Button.module.css
.error { color: red; }
// Button.jsx
import styles from './Button.module.css';
function Button() {
return <button className={styles.error}>Error Button</button>;
}
13. Testing with React Testing Library
Use: Test component behavior.
jsx
Copy
import { render, screen } from '@testing-library/react';
import Button from './Button';
test('renders a button', () => {
render(<Button label="Test" />);
expect(screen.getByText(/Test/i)).toBeInTheDocument();
});
14. Best Practices
Folder Structure:
Copy
src/
components/
hooks/
contexts/
utils/
State Management: Use Redux/Zustand for complex apps.
2. JSX Deep Dive
Use: Mix JavaScript logic with HTML-like syntax.
jsx
Copy
function DynamicList({ items }) {
return (
<ul>
{items.map((item, index) => (
<li key={index}>{item}</li> // Use unique keys for production
))}
</ul>
);
}
3. State Management
useState
Use: Track component-specific data.
jsx
Copy
const [count, setCount] = useState(0);
// Update state based on previous value
setCount(prev => prev + 1);
useReducer
Use: Handle complex state logic.
jsx
Copy
const initialState = { count: 0 };
function reducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
default:
return state;
}
}
const [state, dispatch] = useReducer(reducer, initialState);
// Usage: dispatch({ type: 'increment' });
4. Advanced Hooks
useContext
Use: Access context values globally.
jsx
Copy
const UserContext = createContext();
function App() {
return (
<UserContext.Provider value="Alice">
<Profile />
</UserContext.Provider>
);
}
function Profile() {
const user = useContext(UserContext);
return <div>User: {user}</div>;
}
Custom Hooks
Use: Reuse logic across components.
jsx
Copy
function useWindowWidth() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
const handleResize = () => setWidth(window.innerWidth);
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return width;
}
// Usage: const width = useWindowWidth();
5. Side Effects & Lifecycle
useEffect Cleanup
Use: Prevent memory leaks (e.g., subscriptions).
jsx
Copy
useEffect(() => {
const timer = setInterval(() => console.log('Tick'), 1000);
return () => clearInterval(timer); // Cleanup on unmount
}, []);
6. Forms & Validation
Uncontrolled Components with useRef
Use: Directly access DOM elements.
jsx
Copy
function FileUpload() {
const fileInput = useRef();
const handleSubmit = (e) => {
e.preventDefault();
console.log(fileInput.current.files[0]);
};
return (
<form onSubmit={handleSubmit}>
<input type="file" ref={fileInput} />
<button>Upload</button>
</form>
);
}
Form Validation with react-hook-form
jsx
Copy
import { useForm } from 'react-hook-form';
function LoginForm() {
const { register, handleSubmit, formState: { errors } } = useForm();
const onSubmit = (data) => console.log(data);
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register('email', { required: true })} />
{errors.email && <span>Email is required</span>}
<button type="submit">Submit</button>
</form>
);
}
7. Routing with React Router v6
Use: Nested routes and dynamic parameters.
jsx
Copy
import { Routes, Route, Link, useParams } from 'react-router-dom';
function App() {
return (
<Routes>
<Route path="/" element={<Home />} />
<Route path="/users/:userId" element={<UserProfile />} />
</Routes>
);
}
function UserProfile() {
const { userId } = useParams();
return <h1>User ID: {userId}</h1>;
}
8. State Management with Redux
Use: Global state for large apps.
jsx
Copy
// Store setup
import { configureStore } from '@reduxjs/toolkit';
const store = configureStore({
reducer: {
counter: counterReducer,
},
});
// Slice
const counterSlice = createSlice({
name: 'counter',
initialState: 0,
reducers: {
increment: (state) => state + 1,
},
});
// Component usage
import { useSelector, useDispatch } from 'react-redux';
const count = useSelector(state => state.counter);
const dispatch = useDispatch();
<button onClick={() => dispatch(increment())}>+</button>
9. Error Boundaries
Use: Catch JavaScript errors in components.
jsx
Copy
class ErrorBoundary extends React.Component {
state = { hasError: false };
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, info) {
logErrorToService(error, info);
}
render() {
if (this.state.hasError) {
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
// Usage
<ErrorBoundary>
<BuggyComponent />
</ErrorBoundary>
10. Server-Side Rendering (Next.js)
Use: SEO-friendly pages and faster load times.
jsx
Copy
// pages/index.js (Next.js)
export async function getServerSideProps() {
const res = await fetch('https://api.example.com/data');
const data = await res.json();
return { props: { data } };
}
function HomePage({ data }) {
return <div>{data.message}</div>;
}
11. Performance Optimization
Lazy Loading with React.lazy
Use: Reduce initial bundle size.
jsx
Copy
const HeavyComponent = React.lazy(() => import('./HeavyComponent'));
function App() {
return (
<Suspense fallback={<div>Loading...</div>}>
<HeavyComponent />
</Suspense>
);
}
useMemo for Expensive Calculations
jsx
Copy
const sortedList = useMemo(() => {
return bigList.sort((a, b) => a - b);
}, [bigList]);
12. Testing Advanced Scenarios
Use: Mock API calls and test hooks.
jsx
Copy
// Mock API with Jest
jest.mock('axios', () => ({
get: jest.fn(() => Promise.resolve({ data: 'Mock Data' })),
}));
// Test useEffect and state
test('fetches data on mount', async () => {
render(<DataFetcher />);
await waitFor(() => expect(screen.getByText('Mock Data')).toBeInTheDocument());
});
13. TypeScript with React
Use: Type-safe components.
tsx
Copy
interface UserProps {
name: string;
age: number;
isAdmin?: boolean;
}
const UserCard: React.FC<UserProps> = ({ name, age, isAdmin = false }) => (
<div>
<h2>{name}</h2>
<p>Age: {age}</p>
{isAdmin && <p>Admin User</p>}
</div>
);
14. Deployment
Use: Deploy to Vercel/Netlify.
bash
Copy
# Build the app
npm run build
# Deploy using Vercel CLI
npm install -g vercel
vercel deploy
15. Best Practices & Pitfalls
Immutability: Always return new state objects/arrays.
jsx
Copy
// Bad: Direct mutation
state.items.push(newItem);
// Good: Spread operator
setItems([...items, newItem]);
Keys in Lists: Avoid using array indices for dynamic data.
Dependency Arrays: Include all variables used in useEffect.
16. Advanced Patterns
Render Props
jsx
Copy
function MouseTracker({ render }) {
const [position, setPosition] = useState({ x: 0, y: 0 });
// Track mouse...
return render(position);
}
// Usage
<MouseTracker render={({ x, y }) => <div>X: {x}, Y: {y}</div>} />
Higher-Order Components (HOCs)
jsx
Copy
function withLogger(WrappedComponent) {
return function (props) {
useEffect(() => {
console.log('Component rendered:', WrappedComponent.name);
}, []);
return <WrappedComponent {...props} />;
};
}
17. Ecosystem Tools
Bundlers: Webpack, Parcel.
Styling: Styled Components, Sass.
State Management: Zustand, Jotai.
Data Fetching: React Query, SWR.
18. Resources