Complete React Course

Build Modern User Interfaces

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?

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 = A beautiful sunset; // JSX with children const container = (

Welcome

This is a paragraph.

);

JSX Rules

// Correct JSX const component = (
); // 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}

{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}

); } }
💡 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 ( ); } // 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 (

{title}

{children}
); } // Using the Card component function App() { return (

Name: Alice Johnson

Email: alice@example.com

); }

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}

); }

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 (

{user.name}

{user.email}

); }

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 ; } // 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}
); }

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

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 (
); }

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 ( } /> } /> } /> } /> } /> ); }

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}

); }

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 (

Todo List

setInputValue(e.target.value)} onKeyPress={(e) => e.key === 'Enter' && addTodo()} placeholder="Add a new todo..." />
    {todos.map(todo => (
  • toggleTodo(todo.id)} /> {todo.text}
  • ))}
); }

🏋️ 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