The Complete React Developer's Guide: From Beginner to Professional #
A comprehensive journey through React's core concepts, syntax, and advanced patterns
Table of Contents #
- Introduction to React
- JSX - The Foundation
- Components - Building Blocks
- Props - Component Communication
- State Management
- Lifecycle Methods and Hooks
- Event Handling
- Conditional Rendering
- Lists and Keys
- Forms and User Input
- Context API - Global State
- Refs - DOM Access
- Fragments - Clean JSX
- Error Boundaries
- Higher-Order Components
- Render Props Pattern
- Complete Hooks Guide
- Best Practices and Performance
- Conclusion
Introduction to React #
React is a powerful JavaScript library for building user interfaces, particularly web applications. Created by Facebook in 2013, React has revolutionized how developers approach frontend development by introducing a component-based architecture and declarative programming model.
Why React? #
React solves several fundamental problems in web development:
- Component Reusability: Build once, use anywhere
- Declarative Programming: Describe what you want, not how to achieve it
- Virtual DOM: Efficient updates and rendering
- Unidirectional Data Flow: Predictable state management
- Large Ecosystem: Extensive community and tooling support
Getting Started #
Before diving into React concepts, ensure you have a basic understanding of:
- JavaScript ES6+ features
- HTML and CSS
- DOM manipulation concepts
- NPX/NPM package management
You can start a new React project using Create React App:
npx create-react-app my-appcd my-appnpm start
Now, let's explore React's core concepts systematically.
JSX - The Foundation #
JSX (JavaScript XML) is a syntax extension for JavaScript that looks similar to HTML but is much more powerful. It's the foundation of how we write React components.
Understanding JSX #
JSX allows us to write HTML-like code directly in JavaScript:
const element = <h1>Hello, world!</h1>;
Important: This is neither a string nor HTML. JSX gets compiled to React.createElement() calls:
// JSXconst element = <h1>Hello, world!</h1>; // Compiled to:const element = React.createElement('h1', null, 'Hello, world!');
JSX Rules and Best Practices #
- Single Root Element: JSX expressions must have one parent element
- Closing Tags: All tags must be properly closed
- camelCase Attributes: Use camelCase for attributes (
classNameinstead ofclass) - JavaScript Expressions: Use curly braces for JavaScript expressions
// Good JSXconst name = "John";const element = ( <div> <h1 className="greeting">Hello, {name}!</h1> <img src="avatar.jpg" alt="User avatar" /> </div>); // JavaScript expressions in JSXconst user = { name: "John", age: 30 };const userInfo = ( <div> <h2>{user.name}</h2> <p>Age: {user.age}</p> <p>Can vote: {user.age >= 18 ? "Yes" : "No"}</p> </div>);
JSX vs HTML Differences #
| HTML | JSX |
|---|---|
class | className |
for | htmlFor |
onclick | onClick |
style="color: red" | style={{color: 'red'}} |
Embedding JavaScript in JSX #
JSX's true power comes from embedding JavaScript expressions:
function formatName(user) { return user.firstName + ' ' + user.lastName;} const user = { firstName: 'Harper', lastName: 'Perez'}; const element = ( <h1> Hello, {formatName(user)}! </h1>);
Components - Building Blocks #
Components are the heart of React applications. They encapsulate logic, state, and presentation into reusable pieces.
Functional Components #
Functional components are JavaScript functions that return JSX. They're the modern way to write React components:
// Simple functional componentfunction Welcome(props) { return <h1>Hello, {props.name}</h1>;} // Arrow function syntaxconst Welcome = (props) => { return <h1>Hello, {props.name}</h1>;}; // Implicit return for simple componentsconst Welcome = (props) => <h1>Hello, {props.name}</h1>;
Class Components #
Class components were the original way to write React components with state and lifecycle methods:
class Welcome extends React.Component { render() { return <h1>Hello, {this.props.name}</h1>; }}
Component Composition #
Components can be composed together to build complex UIs:
function App() { return ( <div> <Header /> <MainContent /> <Footer /> </div> );} function Header() { return ( <header> <h1>My Website</h1> <Navigation /> </header> );} function Navigation() { return ( <nav> <ul> <li><a href="/">Home</a></li> <li><a href="/about">About</a></li> <li><a href="/contact">Contact</a></li> </ul> </nav> );}
Component Best Practices #
- Single Responsibility: Each component should have one clear purpose
- Descriptive Names: Use clear, descriptive component names
- Small Components: Keep components small and focused
- Consistent Structure: Maintain consistent file and folder structure
Props - Component Communication #
Props (properties) are how components communicate with each other. They allow parent components to pass data to child components.
Basic Props Usage #
// Parent componentfunction App() { return ( <div> <Welcome name="Sara" age={25} /> <Welcome name="Cahal" age={30} /> <Welcome name="Edite" age={28} /> </div> );} // Child componentfunction Welcome(props) { return ( <div> <h1>Hello, {props.name}</h1> <p>Age: {props.age}</p> </div> );}
Props Destructuring #
Destructuring makes props more readable and easier to work with:
// Without destructuringfunction Welcome(props) { return <h1>Hello, {props.name}</h1>;} // With destructuringfunction Welcome({ name, age, isAdmin }) { return ( <div> <h1>Hello, {name}</h1> <p>Age: {age}</p> {isAdmin && <p>Admin User</p>} </div> );}
Default Props #
Set default values for props:
function Welcome({ name = "Guest", age = 0 }) { return ( <div> <h1>Hello, {name}</h1> <p>Age: {age}</p> </div> );} // Or using defaultProps (class components)class Welcome extends React.Component { static defaultProps = { name: "Guest", age: 0 }; render() { return ( <div> <h1>Hello, {this.props.name}</h1> <p>Age: {this.props.age}</p> </div> ); }}
Props Validation (PropTypes) #
PropTypes help catch bugs by validating props:
import PropTypes from 'prop-types'; function Welcome({ name, age, isAdmin }) { return ( <div> <h1>Hello, {name}</h1> <p>Age: {age}</p> {isAdmin && <p>Admin User</p>} </div> );} Welcome.propTypes = { name: PropTypes.string.isRequired, age: PropTypes.number, isAdmin: PropTypes.bool};
Children Prop #
The special children prop allows components to wrap other components:
function Card({ children, title }) { return ( <div className="card"> <h2>{title}</h2> <div className="card-content"> {children} </div> </div> );} // Usagefunction App() { return ( <Card title="User Profile"> <p>This is the card content</p> <button>Edit Profile</button> </Card> );}
State Management #
State represents data that changes over time. It's what makes React applications interactive and dynamic.
useState Hook (Functional Components) #
The useState hook is the primary way to add state to functional components:
import React, { useState } from 'react'; function Counter() { // Declare a state variable named "count" with initial value 0 const [count, setCount] = useState(0); const increment = () => setCount(count + 1); const decrement = () => setCount(count - 1); const reset = () => setCount(0); return ( <div> <h2>Count: {count}</h2> <button onClick={increment}>+</button> <button onClick={decrement}>-</button> <button onClick={reset}>Reset</button> </div> );}
Multiple State Variables #
You can use multiple state variables in a single component:
function UserProfile() { const [name, setName] = useState(''); const [email, setEmail] = useState(''); const [age, setAge] = useState(0); const [isLoading, setIsLoading] = useState(false); const handleSubmit = async (e) => { e.preventDefault(); setIsLoading(true); try { // API call simulation await updateProfile({ name, email, age }); alert('Profile updated successfully!'); } catch (error) { alert('Error updating profile'); } finally { setIsLoading(false); } }; return ( <form onSubmit={handleSubmit}> <input type="text" value={name} onChange={(e) => setName(e.target.value)} placeholder="Name" /> <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="Email" /> <input type="number" value={age} onChange={(e) => setAge(Number(e.target.value))} placeholder="Age" /> <button type="submit" disabled={isLoading}> {isLoading ? 'Updating...' : 'Update Profile'} </button> </form> );}
State with Objects and Arrays #
When state is an object or array, you need to create new instances:
function TodoList() { const [todos, setTodos] = useState([]); const [inputValue, setInputValue] = useState(''); const addTodo = () => { if (inputValue.trim()) { setTodos([...todos, { id: Date.now(), text: inputValue, completed: false }]); setInputValue(''); } }; const toggleTodo = (id) => { setTodos(todos.map(todo => todo.id === id ? { ...todo, completed: !todo.completed } : todo )); }; const deleteTodo = (id) => { setTodos(todos.filter(todo => todo.id !== id)); }; return ( <div> <input value={inputValue} onChange={(e) => setInputValue(e.target.value)} placeholder="Add a todo..." /> <button onClick={addTodo}>Add</button> <ul> {todos.map(todo => ( <li key={todo.id}> <span style={{ textDecoration: todo.completed ? 'line-through' : 'none' }} onClick={() => toggleTodo(todo.id)} > {todo.text} </span> <button onClick={() => deleteTodo(todo.id)}>Delete</button> </li> ))} </ul> </div> );}
Class Component State #
Class components use this.state and this.setState():
class Counter extends React.Component { constructor(props) { super(props); this.state = { count: 0, name: 'Counter' }; } increment = () => { this.setState({ count: this.state.count + 1 }); }; // setState can accept a function for complex updates incrementAsync = () => { this.setState((prevState) => ({ count: prevState.count + 1 })); }; render() { return ( <div> <h2>{this.state.name}: {this.state.count}</h2> <button onClick={this.increment}>Increment</button> <button onClick={this.incrementAsync}>Increment Async</button> </div> ); }}
Lifecycle Methods and Hooks #
Understanding component lifecycle is crucial for managing side effects, data fetching, and cleanup.
Class Component Lifecycle #
Class components have several lifecycle methods:
class UserProfile extends React.Component { constructor(props) { super(props); this.state = { user: null, loading: true, error: null }; } // Runs after component mounts componentDidMount() { console.log('Component mounted'); this.fetchUser(); } // Runs after component updates componentDidUpdate(prevProps, prevState) { console.log('Component updated'); // Only fetch if user ID changed if (prevProps.userId !== this.props.userId) { this.fetchUser(); } } // Runs before component unmounts componentWillUnmount() { console.log('Component will unmount'); // Cleanup: cancel network requests, clear timers, etc. if (this.requestController) { this.requestController.abort(); } } // Error boundary method static getDerivedStateFromError(error) { return { error: error.message }; } fetchUser = async () => { try { this.setState({ loading: true, error: null }); this.requestController = new AbortController(); const response = await fetch(`/api/users/${this.props.userId}`, { signal: this.requestController.signal }); const user = await response.json(); this.setState({ user, loading: false }); } catch (error) { if (error.name !== 'AbortError') { this.setState({ error: error.message, loading: false }); } } }; render() { const { user, loading, error } = this.state; if (loading) return <div>Loading...</div>; if (error) return <div>Error: {error}</div>; if (!user) return <div>No user found</div>; return ( <div> <h1>{user.name}</h1> <p>{user.email}</p> </div> ); }}
useEffect Hook (Functional Components) #
The useEffect hook handles all lifecycle scenarios in functional components:
import React, { useState, useEffect } from 'react'; function UserProfile({ userId }) { const [user, setUser] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { // This runs after every render (like componentDidMount + componentDidUpdate) console.log('Effect ran'); // Cleanup function (like componentWillUnmount) return () => { console.log('Cleanup'); }; }); // No dependency array = runs after every render // Effect with empty dependency array (like componentDidMount) useEffect(() => { console.log('Component mounted'); return () => { console.log('Component will unmount'); }; }, []); // Empty array = runs once on mount // Effect with dependencies (runs when dependencies change) useEffect(() => { const fetchUser = async () => { try { setLoading(true); setError(null); const controller = new AbortController(); const response = await fetch(`/api/users/${userId}`, { signal: controller.signal }); if (!response.ok) { throw new Error('Failed to fetch user'); } const userData = await response.json(); setUser(userData); } catch (error) { if (error.name !== 'AbortError') { setError(error.message); } } finally { setLoading(false); } }; if (userId) { fetchUser(); } // Cleanup function return () => { // Cancel any ongoing requests controller.abort(); }; }, [userId]); // Runs when userId changes if (loading) return <div>Loading...</div>; if (error) return <div>Error: {error}</div>; if (!user) return <div>No user found</div>; return ( <div> <h1>{user.name}</h1> <p>{user.email}</p> </div> );}
Common useEffect Patterns #
function ComponentWithEffects() { const [count, setCount] = useState(0); const [windowWidth, setWindowWidth] = useState(window.innerWidth); // Data fetching useEffect(() => { fetch('/api/data') .then(response => response.json()) .then(data => console.log(data)); }, []); // Run once on mount // Event listeners useEffect(() => { const handleResize = () => { setWindowWidth(window.innerWidth); }; window.addEventListener('resize', handleResize); return () => { window.removeEventListener('resize', handleResize); }; }, []); // Timers useEffect(() => { const timer = setTimeout(() => { console.log('Timer executed'); }, 1000); return () => clearTimeout(timer); }, [count]); // Reset timer when count changes return ( <div> <p>Count: {count}</p> <p>Window width: {windowWidth}</p> <button onClick={() => setCount(count + 1)}>Increment</button> </div> );}
Event Handling #
React uses its own event system called SyntheticEvents, which provides consistent behavior across different browsers.
Basic Event Handling #
function EventExample() { const [inputValue, setInputValue] = useState(''); const [clickCount, setClickCount] = useState(0); const handleClick = (e) => { e.preventDefault(); // Prevent default behavior setClickCount(clickCount + 1); console.log('Button clicked', e); }; const handleChange = (e) => { setInputValue(e.target.value); }; const handleSubmit = (e) => { e.preventDefault(); alert(`Submitted: ${inputValue}`); }; return ( <form onSubmit={handleSubmit}> <input type="text" value={inputValue} onChange={handleChange} placeholder="Enter text" /> <button type="submit">Submit</button> <button type="button" onClick={handleClick}> Clicked {clickCount} times </button> </form> );}
Event Object Properties #
function EventDetails() { const handleEvent = (e) => { console.log('Event type:', e.type); console.log('Target element:', e.target); console.log('Current target:', e.currentTarget); console.log('Event timestamp:', e.timeStamp); // Mouse events if (e.type.includes('mouse')) { console.log('Mouse position:', e.clientX, e.clientY); } // Keyboard events if (e.type.includes('key')) { console.log('Key pressed:', e.key); console.log('Key code:', e.keyCode); } }; return ( <div> <button onClick={handleEvent} onMouseEnter={handleEvent} onMouseLeave={handleEvent} > Hover and Click Me </button> <input type="text" onKeyDown={handleEvent} onKeyUp={handleEvent} onChange={handleEvent} placeholder="Type here" /> </div> );}
Event Delegation and Binding #
class EventHandlingClass extends React.Component { constructor(props) { super(props); this.state = { message: '' }; // Method 1: Bind in constructor this.handleClick1 = this.handleClick1.bind(this); } handleClick1() { this.setState({ message: 'Method 1: Bound in constructor' }); } // Method 2: Arrow function (auto-binds) handleClick2 = () => { this.setState({ message: 'Method 2: Arrow function' }); }; // Method 3: Bind in render (not recommended) handleClick3() { this.setState({ message: 'Method 3: Bound in render' }); } render() { return ( <div> <p>{this.state.message}</p> <button onClick={this.handleClick1}>Method 1</button> <button onClick={this.handleClick2}>Method 2</button> <button onClick={this.handleClick3.bind(this)}>Method 3</button> </div> ); }}
Passing Arguments to Event Handlers #
function TodoList() { const [todos, setTodos] = useState([ { id: 1, text: 'Learn React', completed: false }, { id: 2, text: 'Build an app', completed: false } ]); const toggleTodo = (id) => { setTodos(todos.map(todo => todo.id === id ? { ...todo, completed: !todo.completed } : todo )); }; const deleteTodo = (id) => { setTodos(todos.filter(todo => todo.id !== id)); }; return ( <ul> {todos.map(todo => ( <li key={todo.id}> <span style={{ textDecoration: todo.completed ? 'line-through' : 'none' }} > {todo.text} </span> {/* Method 1: Arrow function */} <button onClick={() => toggleTodo(todo.id)}> {todo.completed ? 'Undo' : 'Complete'} </button> {/* Method 2: Bind with arguments */} <button onClick={deleteTodo.bind(null, todo.id)}> Delete </button> </li> ))} </ul> );}
Conditional Rendering #
React allows you to render different components or elements based on conditions.
If-Else Statements #
function Greeting({ isLoggedIn, user }) { if (isLoggedIn) { return ( <div> <h1>Welcome back, {user.name}!</h1> <p>You have {user.unreadMessages} unread messages</p> </div> ); } return ( <div> <h1>Please sign in</h1> <button>Sign In</button> </div> );}
Ternary Operator #
function UserStatus({ isLoggedIn, user }) { return ( <div> {isLoggedIn ? ( <div> <h2>Welcome, {user.name}!</h2> <button>Logout</button> </div> ) : ( <div> <h2>Please log in</h2> <button>Login</button> </div> )} </div> );}
Logical AND Operator #
function Notifications({ notifications }) { return ( <div> <h2>Dashboard</h2> {notifications.length > 0 && ( <div className="notifications"> <h3>You have {notifications.length} notifications</h3> {notifications.map(notification => ( <div key={notification.id} className="notification"> {notification.message} </div> ))} </div> )} </div> );}
Complex Conditional Rendering #
function UserProfile({ user, isLoading, error }) { // Multiple conditions const renderContent = () => { if (isLoading) { return <div className="loading">Loading user profile...</div>; } if (error) { return ( <div className="error"> <h3>Error loading profile</h3> <p>{error}</p> <button onClick={() => window.location.reload()}> Try Again </button> </div> ); } if (!user) { return <div>No user data available</div>; } return ( <div className="user-profile"> <img src={user.avatar} alt={user.name} /> <h2>{user.name}</h2> <p>{user.email}</p> {user.isAdmin && <span className="admin-badge">Admin</span>} {user.isPremium && <span className="premium-badge">Premium</span>} </div> ); }; return ( <div> <h1>User Profile</h1> {renderContent()} </div> );}
Conditional Classes and Styles #
function StatusCard({ status, message }) { const cardClass = `status-card ${status === 'success' ? 'success' : status === 'error' ? 'error' : 'info'}`; const cardStyle = { backgroundColor: status === 'success' ? '#d4edda' : status === 'error' ? '#f8d7da' : '#d1ecf1', border: `1px solid ${status === 'success' ? '#c3e6cb' : status === 'error' ? '#f5c6cb' : '#bee5eb'}`, padding: '1rem', borderRadius: '4px' }; return ( <div className={cardClass} style={cardStyle}> <h3>{status.toUpperCase()}</h3> <p>{message}</p> </div> );}
Lists and Keys #
Rendering lists is a common task in React applications. Understanding keys is crucial for performance and avoiding bugs.
Basic List Rendering #
function ShoppingList({ items }) { return ( <ul> {items.map(item => ( <li key={item.id}> {item.name} - ${item.price} </li> ))} </ul> );} // Usageconst groceries = [ { id: 1, name: 'Apples', price: 2.99 }, { id: 2, name: 'Bananas', price: 1.99 }, { id: 3, name: 'Oranges', price: 3.49 }]; function App() { return <ShoppingList items={groceries} />;}
Complex List Components #
function ProductList({ products }) { const [sortBy, setSortBy] = useState('name'); const [filterBy, setFilterBy] = useState('all'); const filteredProducts = products.filter(product => { if (filterBy === 'all') return true; return product.category === filterBy; }); const sortedProducts = [...filteredProducts].sort((a, b) => { if (sortBy === 'name') return a.name.localeCompare(b.name); if (sortBy === 'price') return a.price - b.price; return 0; }); return ( <div> <div className="controls"> <select value={sortBy} onChange={(e) => setSortBy(e.target.value)}> <option value="name">Sort by Name</option> <option value="price">Sort by Price</option> </select> <select value={filterBy} onChange={(e) => setFilterBy(e.target.value)}> <option value="all">All Categories</option> <option value="electronics">Electronics</option> <option value="clothing">Clothing</option> </select> </div> <div className="product-grid"> {sortedProducts.map(product => ( <ProductCard key={product.id} product={product} /> ))} </div> </div> );} function ProductCard({ product }) { return ( <div className="product-card"> <img src={product.image} alt={product.name} /> <h3>{product.name}</h3> <p className="price">${product.price}</p> <p className="category">{product.category}</p> <button>Add to Cart</button> </div> );}
Understanding Keys #
Keys help React identify which items have changed, are added, or are removed:
// Bad: Using array index as keyfunction BadList({ items }) { return ( <ul> {items.map((item, index) => ( <li key={index}>{item.name}</li> ))} </ul> );} // Good: Using unique identifier as keyfunction GoodList({ items }) { return ( <ul> {items.map(item => ( <li key={item.id}>{item.name}</li> ))} </ul> );}
Dynamic Lists with State #
function DynamicList() { const [items, setItems] = useState([ { id: 1, name: 'Item 1', completed: false }, { id: 2, name: 'Item 2', completed: true } ]); const [newItemName, setNewItemName] = useState(''); const addItem = () => { if (newItemName.trim()) { setItems([...items, { id: Date.now(), // Simple ID generation name: newItemName, completed: false }]); setNewItemName(''); } }; const toggleItem = (id) => { setItems(items.map(item => item.id === id ? { ...item, completed: !item.completed } : item )); }; const deleteItem = (id) => { setItems(items.filter(item => item.id !== id)); }; return ( <div> <div> <input type="text" value={newItemName} onChange={(e) => setNewItemName(e.target.value)} placeholder="Add new item" /> <button onClick={addItem}>Add</button> </div> <ul> {items.map(item => ( <li key={item.id}> <span style={{ textDecoration: item.completed ? 'line-through' : 'none' }} onClick={() => toggleItem(item.id)} > {item.name} </span> <button onClick={() => deleteItem(item.id)}>Delete</button> </li> ))} </ul> </div> );}
Nested Lists #
function CategoryList({ categories }) { return ( <div> {categories.map(category => ( <div key={category.id} className="category"> <h3>{category.name}</h3> <ul> {category.items.map(item => ( <li key={item.id}> {item.name} - ${item.price} </li> ))} </ul> </div> ))} </div> );}
Forms and User Input #
Forms are essential for user interaction. React provides two approaches: controlled and uncontrolled components.
Controlled Components #
In controlled components, React state controls the form data:
function ContactForm() { const [formData, setFormData] = useState({ name: '', email: '', message: '', category: 'general', subscribe: false }); const [errors, setErrors] = useState({}); const [isSubmitting, setIsSubmitting] = useState(false); const handleChange = (e) => { const { name, value, type, checked } = e.target; setFormData(prev => ({ ...prev, [name]: type === 'checkbox' ? checked : value })); // Clear error when user starts typing if (errors[name]) { setErrors(prev => ({ ...prev, [name]: '' })); } }; const validateForm = () => { const newErrors = {}; if (!formData.name.trim()) { newErrors.name = 'Name is required'; } if (!formData.email.trim()) { newErrors.email = 'Email is required'; } else if (!/\S+@\S+\.\S+/.test(formData.email)) { newErrors.email = 'Email is invalid'; } if (!formData.message.trim()) { newErrors.message = 'Message is required'; } return newErrors; }; const handleSubmit = async (e) => { e.preventDefault(); const formErrors = validateForm(); if (Object.keys(formErrors).length > 0) { setErrors(formErrors); return; } setIsSubmitting(true); try { // Simulate API call await new Promise(resolve => setTimeout(resolve, 2000)); alert('Form submitted successfully!'); setFormData({ name: '', email: '', message: '', category: 'general', subscribe: false }); } catch (error) { alert('Error submitting form'); } finally { setIsSubmitting(false); } }; return ( <form onSubmit={handleSubmit}> <div> <label htmlFor="name">Name:</label> <input id="name" name="name" type="text" value={formData.name} onChange={handleChange} className={errors.name ? 'error' : ''} /> {errors.name && <span className="error-message">{errors.name}</span>} </div> <div> <label htmlFor="email">Email:</label> <input id="email" name="email" type="email" value={formData.email} onChange={handleChange} className={errors.email ? 'error' : ''} /> {errors.email && <span className="error-message">{errors.email}</span>} </div> <div> <label htmlFor="category">Category:</label> <select id="category" name="category" value={formData.category} onChange={handleChange} > <option value="general">General</option> <option value="support">Support</option> <option value="sales">Sales</option> </select> </div> <div> <label htmlFor="message">Message:</label> <textarea id="message" name="message" value={formData.message} onChange={handleChange} className={errors.message ? 'error' : ''} /> {errors.message && <span className="error-message">{errors.message}</span>} </div> <div> <label> <input name="subscribe" type="checkbox" checked={formData.subscribe} onChange={handleChange} /> Subscribe to newsletter </label> </div> <button type="submit" disabled={isSubmitting}> {isSubmitting ? 'Submitting...' : 'Submit'} </button> </form> );}
Uncontrolled Components #
Uncontrolled components rely on the DOM to handle form data:
function UncontrolledForm() { const nameRef = useRef(); const emailRef = useRef(); const messageRef = useRef(); const handleSubmit = (e) => { e.preventDefault(); const formData = { name: nameRef.current.value, email: emailRef.current.value, message: messageRef.current.value }; console.log('Form data:', formData); // Reset form e.target.reset(); }; return ( <form onSubmit={handleSubmit}> <div> <label htmlFor="name">Name:</label> <input id="name" ref={nameRef} type="text" defaultValue="" required /> </div> <div> <label htmlFor="email">Email:</label> <input id="email" ref={emailRef} type="email" defaultValue="" required /> </div> <div> <label htmlFor="message">Message:</label> <textarea id="message" ref={messageRef} defaultValue="" required /> </div> <button type="submit">Submit</button> </form> );}
Custom Input Components #
function CustomInput({ label, error, ...props }) { return ( <div className="input-group"> <label>{label}</label> <input {...props} className={`input ${error ? 'input-error' : ''}`} /> {error && <span className="error-message">{error}</span>} </div> );} function FormWithCustomInputs() { const [formData, setFormData] = useState({ firstName: '', lastName: '', email: '' }); const [errors, setErrors] = useState({}); const handleChange = (field) => (e) => { setFormData(prev => ({ ...prev, [field]: e.target.value })); }; return ( <form> <CustomInput label="First Name" type="text" value={formData.firstName} onChange={handleChange('firstName')} error={errors.firstName} /> <CustomInput label="Last Name" type="text" value={formData.lastName} onChange={handleChange('lastName')} error={errors.lastName} /> <CustomInput label="Email" type="email" value={formData.email} onChange={handleChange('email')} error={errors.email} /> <button type="submit">Submit</button> </form> );}
Context API - Global State #
The Context API provides a way to share data across the component tree without passing props manually at every level.
Creating and Using Context #
// Create contextconst ThemeContext = React.createContext(); // Provider componentfunction ThemeProvider({ children }) { const [theme, setTheme] = useState('light'); const toggleTheme = () => { setTheme(prev => prev === 'light' ? 'dark' : 'light'); }; const value = { theme, toggleTheme }; return ( <ThemeContext.Provider value={value}> {children} </ThemeContext.Provider> );} // Custom hook to use theme contextfunction useTheme() { const context = useContext(ThemeContext); if (!context) { throw new Error('useTheme must be used within a ThemeProvider'); } return context;} // Components using contextfunction App() { return ( <ThemeProvider> <div className="app"> <Header /> <MainContent /> <Footer /> </div> </ThemeProvider> );} function Header() { const { theme, toggleTheme } = useTheme(); return ( <header className={`header ${theme}`}> <h1>My App</h1> <button onClick={toggleTheme}> Switch to {theme === 'light' ? 'dark' : 'light'} theme </button> </header> );} function MainContent() { const { theme } = useTheme(); return ( <main className={`main ${theme}`}> <p>Current theme: {theme}</p> </main> );}
Multiple Contexts #
// User Contextconst UserContext = React.createContext(); function UserProvider({ children }) { const [user, setUser] = useState(null); const [loading, setLoading] = useState(true); useEffect(() => { // Simulate checking authentication setTimeout(() => { setUser({ id: 1, name: 'John Doe', email: 'john@example.com' }); setLoading(false); }, 1000); }, []); const login = (userData) => { setUser(userData); }; const logout = () => { setUser(null); }; return ( <UserContext.Provider value={{ user, login, logout, loading }}> {children} </UserContext.Provider> );} // Settings Contextconst SettingsContext = React.createContext(); function SettingsProvider({ children }) { const [settings, setSettings] = useState({ notifications: true, darkMode: false, language: 'en' }); const updateSetting = (key, value) => { setSettings(prev => ({ ...prev, [key]: value })); }; return ( <SettingsContext.Provider value={{ settings, updateSetting }}> {children} </SettingsContext.Provider> );} // Combined providersfunction App() { return ( <UserProvider> <SettingsProvider> <ThemeProvider> <Dashboard /> </ThemeProvider> </SettingsProvider> </UserProvider> );} // Component using multiple contextsfunction Dashboard() { const { user, loading } = useContext(UserContext); const { settings } = useContext(SettingsContext); const { theme } = useTheme(); if (loading) return <div>Loading...</div>; return ( <div className={`dashboard ${theme}`}> <h1>Welcome, {user?.name}</h1> <p>Notifications: {settings.notifications ? 'On' : 'Off'}</p> <p>Language: {settings.language}</p> </div> );}
Context with Reducer #
// Actionsconst CART_ACTIONS = { ADD_ITEM: 'ADD_ITEM', REMOVE_ITEM: 'REMOVE_ITEM', UPDATE_QUANTITY: 'UPDATE_QUANTITY', CLEAR_CART: 'CLEAR_CART'}; // Reducerfunction cartReducer(state, action) { switch (action.type) { case CART_ACTIONS.ADD_ITEM: const existingItem = state.items.find(item => item.id === action.payload.id); if (existingItem) { return { ...state, items: state.items.map(item => item.id === action.payload.id ? { ...item, quantity: item.quantity + 1 } : item ) }; } return { ...state, items: [...state.items, { ...action.payload, quantity: 1 }] }; case CART_ACTIONS.REMOVE_ITEM: return { ...state, items: state.items.filter(item => item.id !== action.payload) }; case CART_ACTIONS.UPDATE_QUANTITY: return { ...state, items: state.items.map(item => item.id === action.payload.id ? { ...item, quantity: action.payload.quantity } : item ) }; case CART_ACTIONS.CLEAR_CART: return { ...state, items: [] }; default: return state; }} // Context providerconst CartContext = React.createContext(); function CartProvider({ children }) { const [state, dispatch] = useReducer(cartReducer, { items: [], isOpen: false }); const addItem = (item) => { dispatch({ type: CART_ACTIONS.ADD_ITEM, payload: item }); }; const removeItem = (id) => { dispatch({ type: CART_ACTIONS.REMOVE_ITEM, payload: id }); }; const updateQuantity = (id, quantity) => { dispatch({ type: CART_ACTIONS.UPDATE_QUANTITY, payload: { id, quantity } }); }; const clearCart = () => { dispatch({ type: CART_ACTIONS.CLEAR_CART }); }; const totalItems = state.items.reduce((sum, item) => sum + item.quantity, 0); const totalPrice = state.items.reduce((sum, item) => sum + (item.price * item.quantity), 0); const value = { ...state, addItem, removeItem, updateQuantity, clearCart, totalItems, totalPrice }; return ( <CartContext.Provider value={value}> {children} </CartContext.Provider> );} // Custom hookfunction useCart() { const context = useContext(CartContext); if (!context) { throw new Error('useCart must be used within a CartProvider'); } return context;}
Refs - DOM Access #
Refs provide a way to access DOM nodes or React elements directly.
useRef Hook #
function FocusInput() { const inputRef = useRef(null); const [inputValue, setInputValue] = useState(''); const focusInput = () => { inputRef.current.focus(); }; const clearInput = () => { setInputValue(''); inputRef.current.focus(); }; const selectAllText = () => { inputRef.current.select(); }; return ( <div> <input ref={inputRef} type="text" value={inputValue} onChange={(e) => setInputValue(e.target.value)} placeholder="Type here..." /> <button onClick={focusInput}>Focus Input</button> <button onClick={clearInput}>Clear & Focus</button> <button onClick={selectAllText}>Select All</button> </div> );}
Measuring DOM Elements #
function ElementMeasurer() { const elementRef = useRef(null); const [dimensions, setDimensions] = useState({}); const measureElement = () => { if (elementRef.current) { const rect = elementRef.current.getBoundingClientRect(); setDimensions({ width: rect.width, height: rect.height, top: rect.top, left: rect.left }); } }; useEffect(() => { measureElement(); window.addEventListener('resize', measureElement); return () => { window.removeEventListener('resize', measureElement); }; }, []); return ( <div> <div ref={elementRef} style={{ width: '200px', height: '100px', backgroundColor: 'lightblue', padding: '20px', margin: '20px' }} > Measured Element </div> <div> <h3>Dimensions:</h3> <p>Width: {dimensions.width}px</p> <p>Height: {dimensions.height}px</p> <p>Top: {dimensions.top}px</p> <p>Left: {dimensions.left}px</p> </div> <button onClick={measureElement}>Measure Again</button> </div> );}
Forwarding Refs #
// Forward ref to custom componentsconst CustomInput = React.forwardRef((props, ref) => { return ( <div className="custom-input"> <input ref={ref} {...props} /> </div> );}); function App() { const inputRef = useRef(null); const focusInput = () => { inputRef.current.focus(); }; return ( <div> <CustomInput ref={inputRef} placeholder="Custom input" /> <button onClick={focusInput}>Focus Custom Input</button> </div> );}
Ref Callbacks #
function RefCallback() { const [node, setNode] = useState(null); const measuredRef = useCallback(node => { if (node !== null) { setNode({ width: node.getBoundingClientRect().width, height: node.getBoundingClientRect().height }); } }, []); return ( <div> <div ref={measuredRef} style={{ padding: '20px', backgroundColor: 'lightcoral' }}> Measured with callback ref </div> {node && ( <p>Size: {node.width} x {node.height}</p> )} </div> );}
Fragments - Clean JSX #
Fragments let you group multiple elements without adding extra nodes to the DOM.
Basic Fragments #
// Using React.Fragmentfunction TableRow() { return ( <React.Fragment> <td>Cell 1</td> <td>Cell 2</td> <td>Cell 3</td> </React.Fragment> );} // Using short syntaxfunction TableRowShort() { return ( <> <td>Cell 1</td> <td>Cell 2</td> <td>Cell 3</td> </> );}
Fragments with Keys #
function DescriptionList({ items }) { return ( <dl> {items.map(item => ( <React.Fragment key={item.id}> <dt>{item.term}</dt> <dd>{item.description}</dd> </React.Fragment> ))} </dl> );}
When to Use Fragments #
// Without fragments - creates unnecessary divfunction BadExample() { return ( <div> <h1>Title</h1> <p>Description</p> </div> );} // With fragments - cleaner DOMfunction GoodExample() { return ( <> <h1>Title</h1> <p>Description</p> </> );} // Table example where extra divs would break layoutfunction TableExample() { return ( <table> <tbody> <tr> <TableCells /> </tr> </tbody> </table> );} function TableCells() { return ( <> <td>Name</td> <td>Age</td> <td>City</td> </> );}
Error Boundaries #
Error boundaries catch JavaScript errors in component trees and display fallback UI.
Basic Error Boundary #
class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false, error: null, errorInfo: null }; } static getDerivedStateFromError(error) { // Update state to show fallback UI return { hasError: true }; } componentDidCatch(error, errorInfo) { // Log error details console.error('Error caught by boundary:', error, errorInfo); this.setState({ error: error, errorInfo: errorInfo }); // You can also log the error to an error reporting service // logErrorToService(error, errorInfo); } render() { if (this.state.hasError) { return ( <div className="error-boundary"> <h2>Something went wrong.</h2> <details style={{ whiteSpace: 'pre-wrap' }}> <summary>Error details</summary> {this.state.error && this.state.error.toString()} <br /> {this.state.errorInfo.componentStack} </details> </div> ); } return this.props.children; }}
Advanced Error Boundary #
class AdvancedErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false, error: null, errorInfo: null, eventId: null }; } static getDerivedStateFromError(error) { return { hasError: true }; } componentDidCatch(error, errorInfo) { const eventId = Date.now().toString(); this.setState({ error, errorInfo, eventId }); // Log to external service this.logErrorToService(error, errorInfo, eventId); } logErrorToService = (error, errorInfo, eventId) => { // Simulate logging to external service console.log('Logging error to service:', { eventId, error: error.toString(), stack: error.stack, componentStack: errorInfo.componentStack, timestamp: new Date().toISOString(), userAgent: navigator.userAgent, url: window.location.href }); }; handleReset = () => { this.setState({ hasError: false, error: null, errorInfo: null, eventId: null }); }; render() { if (this.state.hasError) { const { fallback: Fallback } = this.props; if (Fallback) { return ( <Fallback error={this.state.error} resetError={this.handleReset} eventId={this.state.eventId} /> ); } return ( <div className="error-boundary"> <h1>Oops! Something went wrong</h1> <p> We're sorry for the inconvenience. The error has been logged and we'll look into it. </p> <p>Error ID: {this.state.eventId}</p> <button onClick={this.handleReset}>Try again</button> {process.env.NODE_ENV === 'development' && ( <details> <summary>Error details (development only)</summary> <pre>{this.state.error.toString()}</pre> <pre>{this.state.errorInfo.componentStack}</pre> </details> )} </div> ); } return this.props.children; }} // Custom fallback componentfunction ErrorFallback({ error, resetError, eventId }) { return ( <div className="error-fallback"> <h2>Application Error</h2> <p>Something unexpected happened.</p> <pre>{error.message}</pre> <p>Error ID: {eventId}</p> <button onClick={resetError}>Try again</button> </div> );} // Usagefunction App() { return ( <AdvancedErrorBoundary fallback={ErrorFallback}> <Header /> <MainContent /> <Footer /> </AdvancedErrorBoundary> );}
Error Boundary Hook (Custom Implementation) #
// Custom hook for error boundaries in functional componentsfunction useErrorHandler() { const [error, setError] = useState(null); const resetError = () => setError(null); const captureError = (error, errorInfo) => { setError({ error, errorInfo }); console.error('Error captured:', error, errorInfo); }; useEffect(() => { const handleError = (event) => { captureError(event.error, { componentStack: event.error.stack }); }; const handleUnhandledRejection = (event) => { captureError(event.reason, { componentStack: 'Promise rejection' }); }; window.addEventListener('error', handleError); window.addEventListener('unhandledrejection', handleUnhandledRejection); return () => { window.removeEventListener('error', handleError); window.removeEventListener('unhandledrejection', handleUnhandledRejection); }; }, []); return { error, resetError, captureError };} // Usage in functional componentfunction MyComponent() { const { error, resetError, captureError } = useErrorHandler(); const handleRiskyOperation = () => { try { // Risky code here throw new Error('Something went wrong'); } catch (error) { captureError(error, { componentStack: 'MyComponent' }); } }; if (error) { return ( <div> <h3>Error occurred</h3> <p>{error.error.message}</p> <button onClick={resetError}>Try again</button> </div> ); } return ( <div> <button onClick={handleRiskyOperation}>Risky Operation</button> </div> );}
Higher-Order Components #
Higher-Order Components (HOCs) are functions that take a component and return a new component with additional functionality.
Basic HOC #
// HOC that adds loading functionalityfunction withLoading(WrappedComponent) { return function WithLoadingComponent(props) { const [isLoading, setIsLoading] = useState(true); useEffect(() => { const timer = setTimeout(() => setIsLoading(false), 2000); return () => clearTimeout(timer); }, []); if (isLoading) { return <div>Loading...</div>; } return <WrappedComponent {...props} />; };} // Usagefunction UserProfile({ user }) { return ( <div> <h1>{user.name}</h1> <p>{user.email}</p> </div> );} const UserProfileWithLoading = withLoading(UserProfile);


Loading discussion...