React Tutorial
Learn React 19 from your first component to hooks, forms, async UI, performance and real projects. 132 lessons with live React examples that run in your browser, quizzes and projects.
Start learning →
of lessons completed
Getting Started
- Getting Started with React Start learning React 19 with live examples. See what React is, how UI = f(state) works, write your first component in the browser and compare it with plain DOM code.
- How React Works Understand how React turns components into a screen - declarative UI, elements vs components, the render and commit phases, reconciliation, keys and renderers.
- Setting Up a React Project Learn how to start a real React project. Compare Vite, Next.js, React Router and Expo, tour the folder layout, scripts, ESLint hooks rules and DevTools.
- JSX Basics Learn JSX from scratch - what it compiles to, curly-brace expressions, attributes like className and htmlFor, self-closing tags, fragments and how JSX differs from HTML.
- JSX in Depth Go deeper with JSX - spreading props, children as expressions, conditional output with && and ternaries, the 0 pitfall, comments, member expressions and safe HTML.
- The JavaScript You Need for React A focused JavaScript refresher for React learners - destructuring, spread and rest, arrow functions, map/filter/reduce, optional chaining, modules, closures, async and immutability.
- Vite, Bundling and Environment Setup Learn how Vite runs and builds a React app - the dev server, vite.config, VITE_ environment variables, the dist output, preview, and how to analyze bundle size.
Components and Props
- Your First Components Learn what a React component is, how to write function components, name them, nest them into a tree and render the tree with createRoot, with live examples.
- Props Learn how React props work - passing values, destructuring, default values, read-only rules, functions as props, spreading and the children prop - with live code.
- PropTypes, defaultProps and Runtime Prop Validation Learn PropTypes validators, defaultProps, why React 19 removed both for function components, and the modern replacements - default parameter values, TypeScript and runtime schemas.
- Children and Composition Learn React composition - the children prop, slot props, wrapper and layout components, containment, specialization and passing JSX as props, with live examples.
- Conditional Rendering Learn every way to render conditionally in React - if/else, early returns, ternaries, &&, null, switch on state - plus the 0 trap and hiding versus unmounting.
- Rendering Lists and Keys Render lists in React with map(), choose stable keys, see what goes wrong with index keys, filter and sort derived lists, handle empty states and nest lists.
- Keeping Components Pure Learn why React components must be pure functions, what breaks when render mutates outside values, how StrictMode exposes impurity and where side effects belong.
- Styling React Components Learn how to style React components with className, inline style objects, CSS variables, conditional classes, CSS Modules, Tailwind and CSS-in-JS, with accessible focus styles.
- Designing Components Learn how to split a UI into React components, design clean props APIs, decide when to extract, and build a filterable product table step by step using the thinking-in-React method.
- Reusable Widgets: Toggle, Rating, Progress Bar, Breadcrumbs Build accessible reusable React widgets - a toggle switch, a star rating, a progress bar, breadcrumbs, a scroll-aware navbar and a sticky footer layout - with the props, ARIA and keyboard rules each needs.
- Class Components and the Lifecycle Read and migrate legacy React class components - state, setState, componentDidMount, componentDidUpdate, componentWillUnmount and how each one maps to hooks, with runnable examples.
State and Events
- Handling Events Learn how to handle events in React 19 - onClick and onChange, the event object, passing handlers, preventDefault, stopPropagation, bubbling and capture, and keyboard and pointer events.
- State with useState Understand React state with useState - why plain variables fail, the snapshot model, lazy initial values, multiple state variables, state per component instance and resetting state with a key.
- How State Updates Work Learn how React queues and batches state updates, why setCount(count + 1) three times adds only one, how functional updates fix stale values, StrictMode double calls and state versus refs.
- Objects and Arrays in State Learn why React state must be treated as immutable, how to update objects, nested objects and arrays with spread, map and filter, why mutation fails, and how Immer-style produce works.
- Controlled Inputs and Forms Learn controlled inputs in React - text, checkbox, radio, select and textarea, one handler for many fields, submit handling, derived validation and controlled vs uncontrolled.
- Choosing a State Structure Learn how to structure React state - group related values, avoid contradictions, redundancy and duplication, flatten deep nesting and normalize data, with step-by-step refactors.
- Lifting State Up and Sharing State Learn how to lift state up in React - controlled vs uncontrolled components, a single source of truth, accordion and tabs examples, prop drilling and when to stop.
- useReducer and Reducers Learn useReducer in React - actions, pure reducer functions, dispatch, the init function, immutable updates, when to choose reducers over useState, and testing reducers as plain functions.
Hooks
- Effects with useEffect Learn useEffect in React - synchronizing with external systems, when effects run after render, the setup and cleanup lifecycle, StrictMode's extra setup, and effects versus event handlers.
- Effect Dependencies Learn the useEffect dependency array - what counts as a dependency, omitting vs [] vs listing, stale closures, the exhaustive-deps lint rule and how to remove dependencies properly.
- Cleanup, Subscriptions and Timers Learn how useEffect cleanup works in React - intervals, event listeners, subscriptions, AbortController, race conditions and the StrictMode setup, cleanup, setup cycle, with runnable logs.
- You Might Not Need an Effect Learn when not to use useEffect in React - derived state, resetting with keys, event handlers, effect chains, notifying parents and useSyncExternalStore - with before and after examples.
- Refs with useRef Learn useRef in React 19 - mutable values that survive renders, DOM refs for focus and scrolling, refs versus state, callback refs with cleanup, and passing ref as a prop without forwardRef.
- useEffectEvent Learn useEffectEvent in React 19.2 and later - split event-like logic out of effects, read the latest props and state without re-running, avoid stale closures, and know the rules and limits.
- useMemo and useCallback Learn what useMemo and useCallback do in React, when memoization actually helps (expensive work, referential equality), when it doesn't, and how the React Compiler changes the picture.
- useLayoutEffect, useId, useDebugValue and useInsertionEffect Learn useLayoutEffect for measuring the DOM before paint, useId for accessible SSR-safe ids, useDebugValue for DevTools labels and useInsertionEffect for CSS-in-JS, plus a tour of other hooks.
- Custom Hooks Learn to write React custom hooks - extract logic from components, share behavior (not state), build useToggle, useDebounce and a fetch-like hook, compose hooks and decide hooks vs utilities.
- The Rules of Hooks and Common Hook Errors Understand the two rules of hooks and why call order matters, then decode the most common hook errors - conditional hooks, too many re-renders, exhaustive-deps warnings and updates during render.
- Component Lifecycle with Hooks See how a function component mounts, updates and unmounts - render versus commit versus effects, the order of logs, StrictMode double mounts, parent and child order and a key reset.
Context and Shared State
- Context Learn React context with createContext, the Context value provider and useContext. Share theme or user data without prop drilling, understand default values and re-renders, and know when not to use it.
- Context Patterns Practical React context patterns - combine context with useReducer, split state and dispatch, write provider components, stop needless re-renders, use several contexts and inject dependencies for tests.
- External Stores and useSyncExternalStore Learn useSyncExternalStore to connect React to data that lives outside React. Build a tiny store, add selectors, wrap browser APIs like online status and matchMedia, and understand tearing.
- State Management Libraries Compare React state management options - Redux Toolkit, Zustand, Jotai atoms and signals - with runnable hand-written equivalents, the server state versus client state split, and how to choose.
- Classic Redux with react-redux Understand classic Redux and react-redux - createStore, reducers, combineReducers, middleware, redux-thunk, connect, mapStateToProps and selectors - and why Redux Toolkit replaced the boilerplate.
- Redux Toolkit and Zustand Walkthrough A hands-on walkthrough of Redux Toolkit and Zustand - slices, stores, memoized selectors, thunks, middleware and re-render control - with runnable stand-ins and an honest trade-off comparison.
Forms and Actions
- Form Validation Validate React forms the right way - when to show errors (change, blur, submit), accessible messages with aria-describedby, hand-written schemas, multi-step forms and async checks.
- Form Actions in React 19 Learn React 19 form actions - pass a function to the form action prop, read FormData, understand the automatic reset, async actions, formAction buttons and server functions.
- useActionState Learn the React 19 useActionState hook - the (previousState, formData) signature, isPending, state shape for results and errors, queued actions, and when to choose useReducer.
- useFormStatus and useOptimistic Learn useFormStatus to read a parent form's pending state from child components, and useOptimistic to show instant UI updates that roll back when an action fails.
- Uncontrolled Forms, File Inputs and Complex Forms Learn uncontrolled React forms with FormData, refs and defaultValue, handle file inputs and previews, build dynamic field arrays with stable keys, and see how form libraries work.
- React Hook Form with Zod Build fast, validated React forms with React Hook Form and Zod - register, zodResolver, error display, server errors, Controller, field arrays and performance, with runnable stand-ins.
Data and Async
- Fetching Data Fetch data in React with useEffect - loading, error and data states, race conditions, AbortController cleanup, StrictMode double requests, fetch pitfalls and when to use a library.
- The use Hook and Suspense Learn React's use hook and Suspense - reading promises and context during render, loading fallbacks, nested boundaries, skeletons, and the promise identity pitfall.
- Error Boundaries Learn React error boundaries - getDerivedStateFromError, componentDidCatch, resetting, where to place them, what they do not catch, and the onCaughtError root option.
- Transitions, useTransition and useDeferredValue Learn React transitions - urgent versus non-urgent updates, useTransition and isPending, async transitions in React 19, and useDeferredValue with live examples that count renders.
- Caching and Server State Understand server state in React - stale-while-revalidate, query keys, deduping, invalidation - by building a tiny query cache, then see how TanStack Query and SWR do it.
- Async Patterns and Race Conditions Fix out-of-order responses and learn cancellation, debouncing, pagination, retry with backoff, timeouts and optimistic updates with rollback in React, with live examples.
- Axios, HTTP Requests and CORS in React Use Axios in React - instances, interceptors, loading and error states, cancelling requests with AbortController - compare it with fetch, and finally understand what CORS is and how to fix CORS errors.
- TanStack Query in Depth Learn TanStack Query (React Query) in depth - query keys, staleTime and gcTime, dedupe, mutations, invalidation and optimistic updates with rollback, plus runnable stand-ins for the editor.
Performance
- Rendering in Depth Understand React's three steps - trigger, render, commit - what causes a re-render, why rendering is not updating the DOM, batching and StrictMode, with logged live examples.
- memo, Referential Equality and Avoiding Re-renders Learn how React.memo works, why shallow comparison breaks with objects and functions, and the cheaper fixes first - moving state down, lifting content up and passing children.
- Reconciliation and Keys in Depth Understand how React decides to update, reset or remount a component - same type and position, the key prop, index keys, reordering, nested component definitions - with live effect logs.
- Large Lists and Virtualization Render 10,000 rows without freezing the page. Build a windowed list by hand, learn when to paginate instead, and see how react-window, TanStack Virtual and content-visibility fit in.
- Code Splitting with lazy and Suspense Learn code splitting in React with lazy, Suspense and dynamic import() - route-level splits, preloading on hover, transitions, error handling and what bundlers do - with runnable demos.
- The React Compiler What the React Compiler does, how it decides what to cache, the Rules of React it relies on, how to opt in or out, and a runnable model of its compiled output - no more manual memo.
- Profiling and Debugging Performance Measure before you optimize. Use the React DevTools Profiler, the Profiler component, render counters and prop diffing to find wasted renders, plus performance budgets and web vitals.
- SEO, Metadata and Core Web Vitals in React Make a React site easy to find and fast to use - head tags with React 19, why rendering on the server matters for crawlers, streaming, and fixing LCP, INP and CLS.
Advanced Patterns
- Compound Components and Slots Build flexible React components that share hidden state through context. Learn compound components with a Tabs and Accordion, the Children.map trap, accessible wiring and headless hooks.
- Render Props, Higher-Order Components and Hooks Understand render props and higher-order components in React, see why hooks replaced most of them, and learn where render props still shine, plus the HOC pitfalls with refs, statics and remounts.
- Container and Presentational Components Learn the container and presentational component pattern - what each part does, why it makes UI easy to reuse and test, how custom hooks replaced class containers, and when not to split.
- Portals and Overlays Learn React portals with createPortal - render modals and tooltips outside clipped parents, understand event bubbling through portals, trap focus, close on Escape and handle z-index and accessibility.
- The ReactDOM API Tour A tour of react-dom in React 19: createRoot, hydrateRoot, unmount, createPortal, flushSync, resource hints, react-dom/server, and the removed legacy APIs render, hydrate and findDOMNode.
- Refs, forwardRef History and useImperativeHandle Go beyond useRef in React 19 - pass ref as a prop, understand the forwardRef history, expose a small imperative API with useImperativeHandle, use ref callbacks with cleanup, and know when not to.
- Controlled vs Uncontrolled Components Learn who owns the data in React components - controlled and uncontrolled inputs, value vs defaultValue, the switching warnings, a useControllableState hook and how to design components that support both.
- State Machines in React Model React UI with finite state machines - replace boolean flags with named states, write transitions as a reducer, prevent impossible states, handle async flows and timeouts, and know when to use XState.
- Accessibility in React Build accessible React apps: semantic HTML, labels, focus management, ARIA, keyboard navigation, live regions and a custom tabs widget that works for everyone.
- Animation and Transitions Animate React the right way: state-driven CSS transitions, exit animations, requestAnimationFrame hooks, Activity, ViewTransition and prefers-reduced-motion.
- Drag and Drop, Gestures and Pointer Events Build drag and drop in React with HTML5 DnD and pointer events: a sortable list, swipe gestures, touch handling and accessible alternatives.
- Internationalization Make a React app multilingual: Intl for numbers, dates and plurals, a translation context with fallbacks, RTL layouts, react-i18next and FormatJS.
Routing and Apps
- Client-Side Routing Learn how client-side routing works in React by building a tiny hash router with context and hooks: links, params, nested layouts, redirects and 404s.
- React Router and Framework Routers Learn React Router and framework routers: route config, nested layouts, loaders, actions, forms, pending state and framework mode, with runnable mini versions.
- Router Types and Router Hooks Learn the router types (BrowserRouter, HashRouter, MemoryRouter, StaticRouter), the location and history model, the hooks useLocation, useParams, useMatch and useNavigate, and the v5 to v6 mapping.
- App Architecture and Project Structure Organize a growing React app - feature folders, layers, shared UI, a data layer, state placement, environment config, error and loading conventions, monorepos and design systems.
- Authentication and Authorization Patterns Build sign-in flows in React - sessions versus tokens, an auth context, protected routes, role-based UI, token refresh, the OAuth redirect flow, and why you must never trust the client.
- Firebase with React: Auth and Firestore Use Firebase from React - initialize the SDK, build an auth-state hook, read and write Firestore with live listeners, clean up subscriptions, and understand security rules - with runnable stand-ins.
- Server Components, Server Functions and Frameworks Understand React Server Components, the use client and use server directives, server functions, the RSC payload and when you need a framework such as Next.js - with runnable stand-ins.
- Server-Side Rendering and Hydration Learn server-side rendering in React - renderToString, hydrateRoot, hydration mismatches and how to fix them, streaming with Suspense, static generation, and the SEO and speed trade-offs.
Testing and Quality
- Testing React Components Learn how to test React components the way users use them - what to test, React Testing Library queries by role, act, async testing with findBy, and a runnable hand-rolled test harness.
- Testing Hooks, Reducers and Custom Logic Test reducers as plain functions, custom hooks with renderHook, debounced logic with fake timers, fetch with mocks, context with wrappers, and learn when snapshot tests help or hurt.
- End-to-End and Accessibility Testing Test React apps like a real user. Learn end-to-end tests with Playwright and Cypress, automated accessibility checks, keyboard and contrast tests, and how to run them in CI.
- Debugging React Apps Learn a repeatable way to debug React. Read error messages and stacks, understand StrictMode warnings, log renders, use DevTools, and fix the most common bugs.
- Linting, Formatting and Code Quality Keep a React codebase healthy. Set up ESLint with the hooks rules, Prettier, strict TypeScript and pre-commit checks, then use naming rules, a review checklist and dependency hygiene.
- Storybook and Visual Testing Learn Storybook with React - writing stories, args, decorators, play-function interaction tests, accessibility checks and visual regression testing - with runnable stand-ins you can edit.
- React Security: XSS, Tokens and Dependencies Learn the security risks in React apps - cross-site scripting, dangerouslySetInnerHTML and sanitizing, unsafe URLs, token storage, CSRF, secrets in bundles and supply-chain attacks.
TypeScript with React
- TypeScript and React Start using TypeScript with React. Learn what types add, how to type props, children and events, how to read compiler errors, and which parts only exist before the code runs.
- Typing State, Refs, Context and Reducers Type React hooks correctly. Learn useState with unions and null, useRef for DOM nodes and values, createContext defaults, discriminated-union reducers and custom hook return types.
- Generic Components and Advanced Types Build reusable, type-safe React components with TypeScript generics. Learn generic lists, selects and tables, polymorphic as props, ComponentProps, ref types, satisfies and scalable patterns.
Ecosystem
- UI Libraries and Design Systems Compare React component libraries (MUI, Chakra, shadcn/ui, Radix, Headless UI), learn design tokens, theming and headless components, and build a tiny accessible design system.
- Material UI and React Bootstrap in Practice Use Material UI and React Bootstrap in practice - install, core components, ThemeProvider, sx and styled, CssBaseline, grid and layout - with runnable stand-ins that show how theming and variants work.
- The React Ecosystem Map A map of the React ecosystem - routing, data, forms, state, styling, testing, build tools and frameworks - plus how to evaluate dependencies and upgrade React safely.
- React Native, Expo and Beyond the Browser See how React runs outside the browser - React Native and Expo, shared logic, Electron and Tauri, email, PDF and terminal renderers - and build a toy renderer to see how it works.
- Next.js App Router Basics A first tour of the Next.js App Router for React developers - folder-based routes, layouts, loading and error files, server data fetching, server actions, route handlers and metadata.
Projects
- Project: Todo App Build a complete React todo app in four stages - state, a reducer, filtering with derived data, and an accessible editable list with simulated persistence. Every stage runs live.
- Project: Tic-Tac-Toe with History Build tic-tac-toe in React with winner detection and a move history you can jump back through. Learn immutable state, lifting state up and derived values in five runnable stages.
- Project: Shopping Cart Build a shopping cart in React with a cart reducer, context, quantity controls, coupon codes and currency totals formatted with Intl. Five runnable stages with derived state.
- Project: Kanban Board Build a Kanban board in React step by step: columns and cards, a reducer for add, move and delete, keyboard-friendly buttons, and drag and drop with the native browser API.
- Project: Quiz App Build a timed quiz app in React: model the flow as a state machine with useReducer, run a countdown in an effect with cleanup, show the score and add a review mode.
- Project: Search with Debounce and Suspense Build a search-as-you-type interface in React: see why naive fetching shows stale results, then fix it with a debounce hook, cleanup, a promise cache, Suspense and useDeferredValue.
- Project: Markdown Notes App Build a Markdown notes app in React: write a tiny Markdown renderer without dangerouslySetInnerHTML, edit notes with a reducer, add search and pinning, and simulate saving to storage.
- Project: Stopwatch and Countdown Timer Build a stopwatch with laps and a countdown timer in React. Learn why counting ticks drifts, how to measure real elapsed time with useRef, and how to clean up intervals.
- Project: Calculator Build a working calculator in React with a pure reducer that handles digits, operators, equals, clear and errors, then add keyboard support with a safe effect.
- Project: Weather App Build a weather app in React that handles loading, errors, retries and stale responses. Uses a clearly labelled fake API so every example runs in the browser sandbox.
- Project: Memory Card Game Build a memory card matching game in React. Shuffle a deck fairly, track flipped cards, handle matches with a timed flip-back, count moves and detect a win with derived state.
- Project: Typing Speed Tester Build a typing speed tester in React. Compute words per minute and accuracy with pure functions, colour each character as you type, and add a timed mode with an interval.
- Project: Expense Tracker Build an expense tracker in React with a reducer, money stored as integer cents, category totals, a bar chart made from plain elements, filters and a persistence plan.
- Project: Currency Converter Build a currency converter in React in three stages - controlled inputs, derived results from a rates table, and Intl formatting with a swap button and a simulated live-rates load.
- Project: Movie Search App Build a movie search app in React - a debounced search box, loading and empty states, race-safe results and a details view - using a simulated search API that runs in your browser.
- Project: Music Player Build a music player in React - drive the audio element with a ref, keep play state in sync with its events, manage a playlist index and show a progress bar. Uses the site's own chime files.
- Project: Snake Game Build the classic Snake game in React with a pure reducer, a setInterval game loop, keyboard controls, collision detection, scoring, pause and restart - every stage runs live.
- Project: Hangman and Word Guess Build Hangman and a five-letter word guessing game in React. Store only the guesses, derive wrong letters, win and lose, add a physical keyboard, and score duplicate letters correctly.
- Project: Paint App with Canvas Build a drawing app in React with the canvas element - a ref to the canvas, pointer events for mouse, touch and pen, strokes kept in state, and undo, redo and clear that redraw from data.
- Project: Rock Paper Scissors and Dice/Coin Games Build rock paper scissors, a dice roller and a coin flipper in React. Practise randomness, score state, reducers and testable game rules with live editors.
- Project: Small Utility Apps (BMI, Word Counter, Card Validator) Build four small React utilities - a BMI calculator, a word and letter counter, a credit card validator with input masking and a scroll-aware navbar - and learn derived state.
- Project: Password Generator and QR Code Maker Build a secure password generator with crypto.getRandomValues and a QR code maker that draws SVG from your own encoder. Two utilities, live in React.
- Project: Blog App with Routing Build a small blog in React with a hash router you write yourself, route params, a reducer-backed CRUD flow, validated forms, tags and query-string filters.
- Project: Color Palette Generator Build a colour palette generator in React with HSL colour math, locking swatches, keyboard shortcuts, copy to clipboard and WCAG contrast checking.
- Project: 15 Puzzle and Flappy Bird Build a sliding 15 puzzle with a solvable shuffle and animated tiles, then a Flappy Bird game driven by requestAnimationFrame and a pure step function in React.
- Project: Portfolio Site with Animations Build a React portfolio site with a sticky nav, active-section tracking, scroll reveal, parallax, reduced-motion support and animated routes, all without a library.
Practice and Review
- React Cheat Sheet A compact React 19 cheat sheet with runnable examples - JSX rules, props, every hook in one table, state update patterns, Effect rules, form actions and the newest React 19 features.
- Common React Mistakes and How to Fix Them Ten React mistakes every developer makes - missing keys, mutated state, stale closures, effect misuse, conditional hooks, controlled inputs and hydration - each with the real error and the fix.
- Practice Problems: Components, Props and State 15 graded React practice problems on components, props, lists, conditional rendering and state, each with a runnable starter, a hint and a verified solution you can run in your browser.
- Practice Problems: Hooks, Forms and Patterns 15 harder React practice problems on effects, refs, reducers, custom hooks, context, forms, actions, memoization, race conditions, portals and optimistic updates, with verified solutions.
- Machine-Coding Interview Problems in React Prepare for React machine-coding interviews with a repeatable approach and worked solutions - autocomplete, accordion and tabs, pagination, nested checkboxes, infinite scroll and modal - with checklists.
- React Interview Questions and Answers 67 React interview questions with concise, accurate answers: rendering, keys, hooks, state, context, performance, patterns and React 19, plus runnable examples that prove the tricky ones.