1. Introduction to React
React is a JavaScript library for building user interfaces, particularly web applications. It was created by Facebook and is now maintained by Meta and the open-source community.
Why React?
Component-Based: Build encapsulated components that manage their own state
Declarative: Describe what the UI should look like for any given state
Virtual DOM: Efficient updates and rendering
Ecosystem: Rich ecosystem of tools and libraries
Community: Large, active community and job market
React Concepts
App
├── Header
│ ├── Logo
│ └── Navigation
├── Main
│ ├── Sidebar
│ └── Content
└── Footer
💡 Tip: React follows a "learn once, write anywhere" philosophy. You can use React for web, mobile (React Native), and even desktop applications.
2. Setting Up React
Create React App
# Install Node.js first, then:
npx create-react-app my-app
cd my-app
npm start
# Or with Vite (faster)
npm create vite@latest my-react-app -- --template react
cd my-react-app
npm install
npm run dev
Project Structure
my-app/
├── public/
│ ├── index.html
│ └── favicon.ico
├── src/
│ ├── components/
│ ├── App.js
│ ├── App.css
│ ├── index.js
│ └── index.css
├── package.json
└── README.md
Basic React Setup
// index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import './index.css';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
);
3. JSX (JavaScript XML)
What is JSX?
JSX is a syntax extension for JavaScript that looks similar to HTML. It allows you to write HTML-like code in your JavaScript files.
// JSX Example
const element =
Hello, World! ;
// JSX with expressions
const name = 'Alice';
const greeting =
Hello, {name}! ;
// JSX with attributes
const image =
;
// JSX with children
const container = (
Welcome
This is a paragraph.
);
JSX Rules
JSX must return a single parent element
Use className instead of class
Use htmlFor instead of for
Self-closing tags must end with />
Use camelCase for event handlers
// Correct JSX
const component = (
Email:
);
// Using React Fragment
const fragment = (
Title
Paragraph
);
// Short syntax for Fragment
const shortFragment = (
<>
Title
Paragraph
>
);
⚠️ Important: JSX is compiled to JavaScript. Hello becomes React.createElement('h1', null, 'Hello').
4. React Components
Function Components
// Simple function component
function Welcome() {
return
Hello, World! ;
}
// Arrow function component
const Greeting = () => {
return
Welcome to React! ;
};
// Component with parameters
function UserCard({ name, email, avatar }) {
return (
{name}
{email}
);
}
// Using components
function App() {
return (
);
}
Class Components (Legacy)
// Class component (older syntax)
class Welcome extends React.Component {
render() {
return
Hello, {this.props.name}! ;
}
}
// Class component with state
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
increment = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
return (
Count: {this.state.count}
Increment
);
}
}
💡 Tip: Modern React development primarily uses function components with hooks. Class components are still supported but less common in new projects.
5. Props (Properties)
Passing Props
// Parent component
function App() {
const user = {
name: "Alice",
age: 25,
isOnline: true
};
return (
);
}
// Child component
function UserProfile({ name, age, isOnline, hobbies }) {
return (
{name}
Age: {age}
Status: {isOnline ? "Online" : "Offline"}
Hobbies:
{hobbies.map((hobby, index) => (
{hobby}
))}
);
}
Default Props and PropTypes
import PropTypes from 'prop-types';
function Button({ text, color, size, onClick }) {
return (
{text}
);
}
// Default props
Button.defaultProps = {
color: 'primary',
size: 'medium',
text: 'Click me'
};
// PropTypes for type checking
Button.propTypes = {
text: PropTypes.string,
color: PropTypes.oneOf(['primary', 'secondary', 'danger']),
size: PropTypes.oneOf(['small', 'medium', 'large']),
onClick: PropTypes.func.isRequired
};
Children Prop
// Component that uses children
function Card({ title, children }) {
return (
);
}
// Using the Card component
function App() {
return (
Name: Alice Johnson
Email: alice@example.com
Edit Profile
);
}
6. State Management
useState Hook
import React, { useState } from 'react';
function Counter() {
// Declare state variable
const [count, setCount] = useState(0);
const increment = () => {
setCount(count + 1);
};
const decrement = () => {
setCount(count - 1);
};
const reset = () => {
setCount(0);
};
return (
Count: {count}
+
-
Reset
);
}
Complex State
function UserForm() {
const [user, setUser] = useState({
name: '',
email: '',
age: ''
});
const handleInputChange = (e) => {
const { name, value } = e.target;
setUser(prevUser => ({
...prevUser,
[name]: value
}));
};
const handleSubmit = (e) => {
e.preventDefault();
console.log('User data:', user);
};
return (
);
}
State Best Practices:
Don't mutate state directly
Use functional updates for complex state
Keep state as simple as possible
Lift state up when needed by multiple components
7. React Hooks
useEffect Hook
import React, { useState, useEffect } from 'react';
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
// Effect runs after component mounts and when userId changes
useEffect(() => {
const fetchUser = async () => {
setLoading(true);
try {
const response = await fetch(`/api/users/${userId}`);
const userData = await response.json();
setUser(userData);
} catch (error) {
console.error('Error fetching user:', error);
} finally {
setLoading(false);
}
};
fetchUser();
}, [userId]); // Dependency array
// Cleanup effect
useEffect(() => {
const timer = setInterval(() => {
console.log('Timer tick');
}, 1000);
// Cleanup function
return () => {
clearInterval(timer);
};
}, []);
if (loading) return
Loading...
;
if (!user) return
User not found
;
return (
);
}
Custom Hooks
// Custom hook for API calls
function useApi(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const fetchData = async () => {
try {
setLoading(true);
const response = await fetch(url);
if (!response.ok) throw new Error('Failed to fetch');
const result = await response.json();
setData(result);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
};
fetchData();
}, [url]);
return { data, loading, error };
}
// Using the custom hook
function PostList() {
const { data: posts, loading, error } = useApi('/api/posts');
if (loading) return
Loading posts...
;
if (error) return
Error: {error}
;
return (
{posts.map(post => (
{post.title}
{post.content}
))}
);
}
Other Important Hooks
import { useContext, useReducer, useMemo, useCallback } from 'react';
// useContext for consuming context
const ThemeContext = React.createContext();
function ThemedButton() {
const theme = useContext(ThemeContext);
return
Themed Button ;
}
// useReducer for complex state logic
function counterReducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
case 'reset':
return { count: 0 };
default:
throw new Error();
}
}
function Counter() {
const [state, dispatch] = useReducer(counterReducer, { count: 0 });
return (
Count: {state.count}
dispatch({ type: 'increment' })}>+
dispatch({ type: 'decrement' })}>-
dispatch({ type: 'reset' })}>Reset
);
}
8. Event Handling
Handling Events
function EventExamples() {
const [inputValue, setInputValue] = useState('');
const [mousePosition, setMousePosition] = useState({ x: 0, y: 0 });
const handleClick = (e) => {
console.log('Button clicked!', e);
};
const handleInputChange = (e) => {
setInputValue(e.target.value);
};
const handleSubmit = (e) => {
e.preventDefault();
console.log('Form submitted with:', inputValue);
};
const handleMouseMove = (e) => {
setMousePosition({ x: e.clientX, y: e.clientY });
};
const handleKeyDown = (e) => {
if (e.key === 'Enter') {
console.log('Enter key pressed!');
}
};
return (
Event Handling Examples
Click me
Mouse position: {mousePosition.x}, {mousePosition.y}
);
}
Event Object and Synthetic Events
function EventDetails() {
const handleEvent = (e) => {
// SyntheticEvent properties
console.log('Event type:', e.type);
console.log('Target element:', e.target);
console.log('Current target:', e.currentTarget);
// Prevent default behavior
e.preventDefault();
// Stop event propagation
e.stopPropagation();
// Access native event
console.log('Native event:', e.nativeEvent);
};
return (
Click for event details
);
}
9. React Router
Setting up React Router
# Install React Router
npm install react-router-dom
# Basic setup
import { BrowserRouter, Routes, Route, Link } from 'react-router-dom';
function App() {
return (
Home
About
Contact
} />
} />
} />
} />
} />
);
}
Navigation and Parameters
import { useParams, useNavigate, useLocation } from 'react-router-dom';
function UserProfile() {
const { id } = useParams();
const navigate = useNavigate();
const location = useLocation();
const goBack = () => {
navigate(-1); // Go back one page
};
const goToUsers = () => {
navigate('/users');
};
return (
User Profile {id}
Current path: {location.pathname}
Go Back
All Users
);
}
10. Practice Projects
Todo List Application
import React, { useState } from 'react';
function TodoApp() {
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 (
);
}
🏋️ Project Ideas:
Build these projects to master React:
Weather App: Fetch weather data from an API
Movie Database: Search and display movies
Shopping Cart: Add/remove items, calculate totals
Blog Platform: Create, edit, and delete posts
Chat Application: Real-time messaging
E-commerce Store: Product catalog with cart
Next Steps
Advanced React Topics:
State Management: Redux, Zustand, Context API
Testing: Jest, React Testing Library
Performance: React.memo, useMemo, useCallback
Styling: Styled Components, CSS Modules
Forms: Formik, React Hook Form
Animation: Framer Motion, React Spring
🎉 Congratulations!
You've learned the fundamentals of React! You can now build modern, interactive user interfaces.
Continue practicing with projects and explore the React ecosystem!