Category: React Tutorials

  • React Router — Multi-Page Navigation (React 19+)

    Updated July 4, 2026. Refreshed for React 19 and current SEO best practices.

    React 19 Notes

    React Router v6 uses a declarative <Routes> API with nested <Outlet /> layouts. For SEO-critical pages, pair React skills with Next.js or prerender key routes on your static host.

    This lesson introduces React Router — the standard library for client-side routing in React SPAs. You will install react-router-dom, define routes, navigate with Link, read URL parameters, and structure a small multi-page app.

    Prerequisites: Lessons 1–6 with a Vite React project. Estimated time: 50–60 minutes.

    1. Why Client-Side Routing?

    Without a router, a React app is a single view. Users expect URLs like /about and /users/42 that work with bookmarks and the back button. React Router maps URLs to components without full page reloads.

    React single-page application routing
    Photo by Mohammad Rahmani on Unsplash

    2. Install react-router-dom

    npm install react-router-dom
    

    React Router v6+ is the current API. It works with Vite and React 19 out of the box.

    3. Basic Route Setup

    Wrap your app in BrowserRouter and define routes in main.jsx or App.jsx:

    import { BrowserRouter, Routes, Route } from 'react-router-dom';
    import Home from './pages/Home';
    import About from './pages/About';
    import NotFound from './pages/NotFound';
    
    function App() {
      return (
        <BrowserRouter>
          <Routes>
            <Route path="/" element={<Home />} />
            <Route path="/about" element={<About />} />
            <Route path="*" element={<NotFound />} />
          </Routes>
        </BrowserRouter>
      );
    }
    
    export default App;
    

    Create simple page components under src/pages/ — each returns a heading and paragraph for now.

    import { Link, NavLink } from 'react-router-dom';
    
    function Navbar() {
      return (
        <nav>
          <Link to="/">Home</Link>
          <NavLink
            to="/about"
            style={({ isActive }) => ({ fontWeight: isActive ? 'bold' : 'normal' })}
          >
            About
          </NavLink>
        </nav>
      );
    }
    

    Use Link instead of <a href> for internal routes — it prevents full reloads. NavLink adds an isActive callback for styling the current page.

    5. URL Parameters

    // Route definition
    <Route path="/lessons/:slug" element={<LessonDetail />} />
    
    // LessonDetail.jsx
    import { useParams } from 'react-router-dom';
    
    function LessonDetail() {
      const { slug } = useParams();
      return <h1>Lesson: {slug}</h1>;
    }
    

    Dynamic segments (:slug) are common for blog posts, product pages, and user profiles — core patterns in a react router tutorial.

    6. Layout Routes with Outlet

    function Layout() {
      return (
        <>
          <Navbar />
          <main>
            <Outlet />
          </main>
        </>
      );
    }
    
    // Routes
    <Route element={<Layout />}>
      <Route path="/" element={<Home />} />
      <Route path="/about" element={<About />} />
    </Route>
    

    Outlet renders the matched child route — shared nav and footer without duplicating markup.

    7. Programmatic Navigation

    import { useNavigate } from 'react-router-dom';
    
    function LoginForm() {
      const navigate = useNavigate();
    
      function onSuccess() {
        navigate('/dashboard', { replace: true });
      }
    }
    

    Use navigate after form submit or logout. replace: true avoids stacking history entries.

    8. Vite and Production Deploy

    For SPAs on static hosts, configure the server to fallback to index.html for unknown paths — otherwise refreshing /about returns 404. Vite dev server handles this automatically; production depends on your host (Netlify, Vercel, nginx rewrite rules).

    9. Next Steps

    You now have a seven-lesson foundation: setup, JSX, state, effects, forms, and routing. Explore Angular tutorials for a full-framework comparison, or join Alkademy for live React projects.

    Series: Lesson 6 · Tutorial hub

    Frequently Asked Questions

    What is React Router used for?
    React Router maps URL paths to React components, enabling multi-page navigation in single-page applications without full browser reloads.

    React Router vs Next.js routing?
    React Router is client-side only — ideal for Vite SPAs. Next.js includes file-based routing with server rendering for SEO-heavy sites.

    How do I protect routes that require login?
    Create a wrapper component that checks auth state and redirects with Navigate to="/login" or useNavigate when the user is not authenticated.


    Want live React or frontend classes? Join Alkademy for instructor-led React and JavaScript courses with hands-on projects.

  • React Forms — Controlled Inputs and Validation (React 19+)

    React Forms — Controlled Inputs and Validation (React 19+)

    Updated July 4, 2026. Refreshed for React 19 and current SEO best practices.

    React 19 Notes

    Controlled inputs keep a single source of truth in React state — ideal for validation and reset. React 19 form actions (Server Actions) shine in Next.js; in Vite SPAs, useState remains the standard beginner pattern.

    This lesson teaches React forms using controlled components — inputs whose value is driven by React state. You will handle submit events, validate fields, show error messages, and build a complete signup form.

    Prerequisites: Lessons 1–5, especially useState. Estimated time: 45–55 minutes.

    1. Controlled vs Uncontrolled Inputs

    A controlled input stores its value in state and updates via onChange:

    const [email, setEmail] = useState('');
    
    <input
      type="email"
      value={email}
      onChange={(e) => setEmail(e.target.value)}
    />
    

    An uncontrolled input uses a DOM ref — fine for simple cases, but controlled inputs are easier to validate and reset in React apps.

    React controlled form with validation
    Photo by Team Nocoloco on Unsplash

    2. Form State as an Object

    const [form, setForm] = useState({
      name: '',
      email: '',
      password: '',
    });
    
    function handleChange(e) {
      const { name, value } = e.target;
      setForm((prev) => ({ ...prev, [name]: value }));
    }
    

    Use the name attribute on each input to update the correct field without separate handlers.

    User filling out a web form
    Photo by Glenn Carstens-Peters on Unsplash

    3. Handling Submit

    function handleSubmit(e) {
      e.preventDefault();
      console.log('Submitting', form);
      // POST to API or update parent state
    }
    
    return (
      <form onSubmit={handleSubmit}>
        {/* inputs */}
        <button type="submit">Sign up</button>
      </form>
    );
    

    Always call e.preventDefault() unless you want a full page reload.

    4. Simple Validation

    const [errors, setErrors] = useState({});
    
    function validate() {
      const next = {};
      if (!form.name.trim()) next.name = 'Name is required';
      if (!form.email.includes('@')) next.email = 'Valid email required';
      if (form.password.length < 8) next.password = 'Minimum 8 characters';
      setErrors(next);
      return Object.keys(next).length === 0;
    }
    
    function handleSubmit(e) {
      e.preventDefault();
      if (!validate()) return;
      // proceed with valid data
    }
    

    Show errors next to fields: {errors.email && <span>{errors.email}</span>}. For larger apps consider React Hook Form or Zod — out of scope for this beginner react forms tutorial.

    5. Complete Example — SignupForm

    import { useState } from 'react';
    
    function SignupForm() {
      const [form, setForm] = useState({ name: '', email: '', password: '' });
      const [errors, setErrors] = useState({});
      const [submitted, setSubmitted] = useState(false);
    
      function handleChange(e) {
        const { name, value } = e.target;
        setForm((prev) => ({ ...prev, [name]: value }));
      }
    
      function validate() {
        const next = {};
        if (!form.name.trim()) next.name = 'Name is required';
        if (!form.email.includes('@')) next.email = 'Enter a valid email';
        if (form.password.length < 8) next.password = 'Use at least 8 characters';
        setErrors(next);
        return Object.keys(next).length === 0;
      }
    
      function handleSubmit(e) {
        e.preventDefault();
        if (!validate()) return;
        setSubmitted(true);
      }
    
      if (submitted) {
        return <p>Thanks, {form.name}! Check {form.email} to confirm.</p>;
      }
    
      return (
        <form onSubmit={handleSubmit} style={{ maxWidth: '360px' }}>
          <label>
            Name
            <input name="name" value={form.name} onChange={handleChange} />
            {errors.name && <small style={{ color: 'crimson' }}>{errors.name}</small>}
          </label>
          <label>
            Email
            <input name="email" type="email" value={form.email} onChange={handleChange} />
            {errors.email && <small style={{ color: 'crimson' }}>{errors.email}</small>}
          </label>
          <label>
            Password
            <input name="password" type="password" value={form.password} onChange={handleChange} />
            {errors.password && <small style={{ color: 'crimson' }}>{errors.password}</small>}
          </label>
          <button type="submit">Create account</button>
        </form>
      );
    }
    
    export default SignupForm;
    

    Add basic CSS (stack labels with display: block and margin) and test invalid submissions to see validation messages.

    6. Checkbox and Select

    <input
      type="checkbox"
      checked={form.agree}
      onChange={(e) => setForm((prev) => ({ ...prev, agree: e.target.checked }))}
    />
    
    <select
      name="plan"
      value={form.plan}
      onChange={handleChange}
    >
      <option value="free">Free</option>
      <option value="pro">Pro</option>
    </select>
    

    7. Next Steps

    Forms capture user input; routing sends users between pages. Next you will add React Router for multi-page navigation in a single-page app.

    Series: Lesson 5 · Lesson 7 — React Router

    Frequently Asked Questions

    What is a controlled component in React?
    A controlled component is an input whose value is stored in React state and updated through onChange, giving React full control over the field.

    Should I use a form library?
    For learning and small forms, plain useState is enough. Libraries like React Hook Form reduce re-renders and simplify validation in large apps.

    How do I reset a form after submit?
    Call setForm({ name: '', email: '', password: '' }) and setErrors({}) after a successful submit.


    Want live React or frontend classes? Join Alkademy for instructor-led React and JavaScript courses with hands-on projects.

  • React useEffect — Side Effects and Data Fetching (React 19+)

    React useEffect — Side Effects and Data Fetching (React 19+)

    Updated July 4, 2026. Refreshed for React 19 and current SEO best practices.

    React 19 Notes

    Use AbortController to cancel in-flight fetches when components unmount. For data-heavy apps consider TanStack Query; for this series, useEffect + fetch teaches the fundamentals clearly.

    This lesson explains React useEffect — the hook for side effects that run after render: fetching data, timers, DOM subscriptions, and syncing with external systems. You will fetch JSON from a public API and clean up resources correctly.

    Prerequisites: Lessons 1–4, especially useState. Estimated time: 50–60 minutes.

    1. What Is a Side Effect?

    A side effect is work that reaches outside the component’s render output: network requests, localStorage, document.title, WebSocket listeners, or setInterval. React expects render to be pure — effects belong in useEffect.

    Fetching API data in a React application
    Photo by Luke Chesser on Unsplash

    2. useEffect Syntax

    import { useEffect, useState } from 'react';
    
    function PageTitle({ title }) {
      useEffect(() => {
        document.title = title;
      }, [title]);
    
      return <h1>{title}</h1>;
    }
    

    The second argument is the dependency array. React re-runs the effect when any dependency changes. An empty array [] runs once after mount (like componentDidMount).

    JavaScript developer working with async data
    Photo by Florian Olivo on Unsplash

    3. Fetch Data on Mount

    function UserList() {
      const [users, setUsers] = useState([]);
      const [loading, setLoading] = useState(true);
      const [error, setError] = useState(null);
    
      useEffect(() => {
        async function loadUsers() {
          try {
            const res = await fetch('https://jsonplaceholder.typicode.com/users');
            if (!res.ok) throw new Error('Failed to fetch');
            const data = await res.json();
            setUsers(data);
          } catch (err) {
            setError(err.message);
          } finally {
            setLoading(false);
          }
        }
        loadUsers();
      }, []);
    
      if (loading) return <p>Loading…</p>;
      if (error) return <p>Error: {error}</p>;
    
      return (
        <ul>
          {users.map((user) => (
            <li key={user.id}>{user.name}</li>
          ))}
        </ul>
      );
    }
    

    This pattern — loading, error, and data state — is standard in production React apps and frameworks like Next.js.

    4. Cleanup Functions

    Return a function from useEffect to clean up before the effect runs again or when the component unmounts:

    useEffect(() => {
      const id = setInterval(() => console.log('tick'), 1000);
      return () => clearInterval(id);
    }, []);
    

    Always clean up subscriptions, timers, and event listeners to prevent memory leaks — a core topic in any react useeffect tutorial.

    5. Dependency Array Pitfalls

    • Missing deps — stale closures; ESLint react-hooks/exhaustive-deps warns you
    • Object/array deps — new reference every render causes infinite loops; memoize or lift state
    • No array — effect runs after every render (rarely what you want)

    6. Abort Fetch on Unmount (React 19)

    useEffect(() => {
      const controller = new AbortController();
    
      fetch(url, { signal: controller.signal })
        .then((res) => res.json())
        .then(setData)
        .catch((err) => {
          if (err.name !== 'AbortError') setError(err.message);
        });
    
      return () => controller.abort();
    }, [url]);
    

    Aborting prevents setting state on an unmounted component — especially important in React Strict Mode where effects run twice in development.

    7. Next Steps

    Effects connect React to the outside world. Next you will build controlled forms with state and validation patterns used in real apps.

    Series: Lesson 4 · Lesson 6 — Forms

    Frequently Asked Questions

    When should I use useEffect?
    Use it when you need to synchronize with something outside React’s render — APIs, browser APIs, third-party widgets, or timers.

    Can I fetch data without useEffect?
    Yes. React 19 and frameworks like Next.js support fetching in Server Components or with libraries like TanStack Query. useEffect fetch is still the standard pattern in client-only Vite SPAs.

    Why does my useEffect run twice in development?
    React Strict Mode intentionally double-invokes effects in development to surface cleanup bugs. Production behavior runs once per dependency change.


    Want live React or frontend classes? Join Alkademy for instructor-led React and JavaScript courses with hands-on projects.

  • React State and useState — Interactive UI (React 19+)

    React State and useState — Interactive UI (React 19+)

    Updated July 4, 2026. Refreshed for React 19 and current SEO best practices.

    React 19 Notes

    React 19 batches state updates for performance. Prefer functional updaters setState(s => ...) when the next value depends on the previous one. The React Compiler can optimize many components automatically — still follow the Rules of Hooks.

    This lesson covers React state and the useState hook — how components remember data that changes over time and re-render when that data updates. You will handle events, update state safely, and build a small counter and like-button example.

    Prerequisites: Lessons 1–3 (Introduction, Setup, JSX and Components) with a Vite React project. Estimated time: 45–55 minutes.

    1. Props vs State

    Props flow down from parent to child and never change inside the child. State is private data owned by a component — when state changes, React re-renders that component and its children with the new UI.

    Rule of thumb: if data should change because the user clicked, typed, or a timer fired, it belongs in state (or a state library later). If data is configuration from a parent, use props.

    Interactive React UI with state
    Photo by Joshua Reddekopp on Unsplash

    2. The useState Hook

    Import and call useState at the top of a function component:

    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>
      );
    }
    
    export default Counter;
    

    useState(initialValue) returns a pair: the current value and a setter function. Always update state with the setter — never assign directly to count.

    Developer building React stateful components
    Photo by Florian Olivo on Unsplash

    3. Handling Events

    React uses camelCase event names and passes functions, not strings:

    <button onClick={handleClick}>Click me</button>
    <input onChange={(e) => setName(e.target.value)} />
    

    Common events: onClick, onChange, onSubmit, onKeyDown. Prevent default form behavior with e.preventDefault() inside onSubmit.

    4. Functional State Updates

    When the next state depends on the previous state, pass a function to the setter:

    setCount((prev) => prev + 1);
    

    This avoids stale closures when multiple updates happen in one event or in async code — a common react usestate tutorial gotcha.

    5. Multiple State Variables

    Split unrelated data into separate useState calls:

    const [likes, setLikes] = useState(0);
    const [liked, setLiked] = useState(false);
    

    For complex objects, you can use one state object, but prefer separate variables until you need to group them (or use useReducer in advanced apps).

    6. Complete Example — LikeButton

    Create src/LikeButton.jsx:

    import { useState } from 'react';
    
    function LikeButton({ initialLikes = 0 }) {
      const [likes, setLikes] = useState(initialLikes);
      const [liked, setLiked] = useState(false);
    
      function toggleLike() {
        setLiked((prev) => !prev);
        setLikes((prev) => (liked ? prev - 1 : prev + 1));
      }
    
      return (
        <button
          onClick={toggleLike}
          style={{
            padding: '0.5rem 1rem',
            borderRadius: '6px',
            border: '1px solid #e2e8f0',
            background: liked ? '#eff6ff' : '#fff',
            cursor: 'pointer',
          }}
        >
          {liked ? '♥' : '♡'} {likes} likes
        </button>
      );
    }
    
    export default LikeButton;
    

    Wire it in App.jsx alongside your Lesson 3 components. Run npm run dev and confirm the count updates on each click.

    7. Rules of Hooks

    • Only call hooks at the top level of a function component — not inside loops, conditions, or nested functions
    • Only call hooks from React function components or custom hooks
    • Hook names start with use by convention

    React 19’s compiler can optimize many patterns, but these rules still apply to useState, useEffect, and other hooks.

    8. Next Steps

    State makes UIs interactive. Next you will learn useEffect for side effects such as fetching data, subscribing to events, and syncing with the browser API.

    Series: Lesson 3 · Lesson 5 — useEffect

    Frequently Asked Questions

    What is useState in React?
    useState is a hook that adds local state to a function component. It returns the current value and a function to update it, triggering a re-render.

    Why does my React state not update immediately?
    State updates are asynchronous and batched. Use the functional setter form setCount(c => c + 1) when the next value depends on the previous one.

    Can I use useState for objects and arrays?
    Yes. When updating objects or arrays, create a new copy (spread or map) instead of mutating the existing value — React compares by reference.


    Want live React or frontend classes? Join Alkademy for instructor-led React and JavaScript courses with hands-on projects.

  • React JSX and Components — Build Your First UI

    React JSX and Components — Build Your First UI

    Updated July 4, 2026. Refreshed for React 19 and current SEO best practices.

    React 19 Notes

    React 19 uses the automatic JSX runtime — write components as plain functions returning JSX. Use Fragment (<>...</>) to group elements without extra DOM nodes. Props are read-only; state and hooks come in later lessons.

    This lesson covers React JSX and components — the core skills for building any React interface. You will learn JSX rules, write functional components, pass props, render conditionally, and combine everything in a small Greeting Card example.

    Prerequisites: Lessons 1–2 (Introduction, Setup) with a Vite React project running locally. Estimated time: 45–55 minutes.

    1. What Is JSX?

    JSX (JavaScript XML) lets you write HTML-like markup inside JavaScript. React compiles JSX into React.createElement calls (or equivalent) that describe UI structure.

    Example:

    const element = <h1 className="title">Hello, JSX</h1>;
    

    Important JSX rules:

    • Use className instead of class (since class is a JavaScript keyword)
    • Self-closing tags must end with /> — e.g. <img />, <br />
    • Return a single parent element, or use a Fragment (<>...</>)
    • Embed JavaScript expressions inside curly braces: {userName}, {2 + 2}
    • Comments inside JSX: {/* comment */}
    React component-based user interface
    Photo by Lautaro Andreani on Unsplash

    2. Functional Components

    A component is a reusable function (or class) that returns JSX. Modern React uses function components almost exclusively:

    function Welcome() {
      return <h2>Welcome to the React tutorial</h2>;
    }
    
    export default Welcome;
    

    Use a component like an HTML tag: <Welcome />. Compose small components into larger ones — this is how React apps scale without spaghetti DOM code.

    File naming convention: PascalCase for components (GreetingCard.jsx), camelCase for utilities (formatDate.js).

    JavaScript code for React JSX and components
    Photo by Florian Olivo on Unsplash

    3. Props — Passing Data to Components

    Props (properties) are read-only inputs from a parent component. Define them as function parameters:

    function Greeting({ name, role }) {
      return (
        <div>
          <h3>Hello, {name}!</h3>
          <p>Role: {role}</p>
        </div>
      );
    }
    
    // Usage in App.jsx:
    // <Greeting name="Kindson" role="Developer" />
    

    Props make components reusable: the same Greeting component renders different content depending on what the parent passes. Never mutate props inside a child — treat them as immutable.

    Default values (optional):

    function Greeting({ name = 'Guest', role = 'Learner' }) {
      return <p>{name} — {role}</p>;
    }
    

    4. Conditional Rendering

    Show different UI based on data using JavaScript expressions inside JSX:

    function StatusMessage({ isOnline }) {
      return (
        <p>
          {isOnline ? 'You are online' : 'You are offline'}
        </p>
      );
    }
    

    Other patterns:

    • Logical AND{hasError && <p>Error occurred</p>}
    • Early return — return different JSX from separate if branches before the main return
    • Variable assignment — set let content = ... then render {content}

    5. Rendering Lists (Preview)

    Render arrays with .map() and always provide a stable key prop:

    const lessons = ['Introduction', 'Setup', 'JSX'];
    
    function LessonList() {
      return (
        <ul>
          {lessons.map((title, index) => (
            <li key={index}>{title}</li>
          ))}
        </ul>
      );
    }
    

    We cover lists and keys in depth in a future lesson. For now, remember that key helps React identify which items changed.

    6. Fragments — Group Without Extra DOM Nodes

    JSX requires one parent element. Wrapping in <div> adds unnecessary DOM nodes. Use a Fragment instead:

    function TitleBlock() {
      return (
        <>
          <h1>React JSX and Components</h1>
          <p>Lesson 3</p>
        </>
      );
    }
    

    Long form: <React.Fragment>...</React.Fragment> — useful when you need a key on a fragment in a list.

    7. Complete Example — GreetingCard

    Create src/GreetingCard.jsx:

    function GreetingCard({ name, title, isPremium }) {
      return (
        <article
          style={{
            border: '1px solid #e2e8f0',
            borderRadius: '8px',
            padding: '1.25rem',
            maxWidth: '320px',
          }}
        >
          <h2>{title}</h2>
          <p>Hello, <strong>{name}</strong>!</p>
          {isPremium ? (
            <span style={{ color: '#2563eb' }}>Premium member</span>
          ) : (
            <span>Free tier</span>
          )}
        </article>
      );
    }
    
    export default GreetingCard;
    

    Update src/App.jsx:

    import GreetingCard from './GreetingCard';
    
    function App() {
      return (
        <main style={{ padding: '2rem', fontFamily: 'system-ui' }}>
          <h1>React JSX and Components</h1>
          <GreetingCard name="Kindson" title="Welcome" isPremium={true} />
          <GreetingCard name="Guest" title="Welcome" isPremium={false} />
        </main>
      );
    }
    
    export default App;
    

    Run npm run dev and verify both cards render with different props. You have built a small, reusable react jsx components example.

    8. Styling Components (Brief)

    This lesson uses inline style={{ ... }} objects for clarity. In production you might use:

    • CSS modules (Component.module.css)
    • Tailwind CSS utility classes
    • Styled-components or CSS-in-JS libraries

    Styling choice does not change component structure — props and JSX work the same way.

    9. Next Steps

    You can now write functional components with JSX, props, and conditional rendering. Next: Lesson 4 — React State and useState.

    Series links: Lesson 1 · Lesson 2

    Frequently Asked Questions

    What is JSX in React?
    JSX is a syntax extension that lets you write HTML-like markup inside JavaScript. React compiles JSX into efficient JavaScript function calls.

    What is the difference between props and state?
    Props are read-only inputs passed from a parent component. State is mutable data managed inside a component (covered in a later lesson on hooks).

    Why do I need keys in lists?
    Keys help React identify which list items changed, were added, or removed — improving update performance and avoiding subtle bugs.


    Want live React or frontend classes? Join Alkademy for instructor-led React and JavaScript courses with hands-on projects.

  • React Setup — Create Your First App with Vite

    React Setup — Create Your First App with Vite

    Updated July 4, 2026. Refreshed for React 19 and current SEO best practices.

    React 19 Notes

    Use Node.js 20 LTS or newer. Scaffold projects with npm create vite@latest and choose the React template. Install the ES7+ React/Redux/React-Native snippets extension in VS Code for faster component authoring.

    In this lesson you will complete your React setup using Vite — the fast, modern build tool recommended for new React projects in 2026. By the end you will have a running dev server and a hello-world component you can edit live in the browser.

    Prerequisites: Lesson 1 (React Introduction). Estimated time: 40–50 minutes.

    1. Install Node.js 20+

    React development requires Node.js (which includes npm, the package manager). Download the LTS version from nodejs.org.

    Verify the installation in your terminal (Terminal on Mac, PowerShell or Windows Terminal on Windows):

    node --version
    npm --version
    

    You should see Node v20.x or newer and npm 10.x or newer. If either command fails, restart the terminal after installing Node.

    VS Code editor for React development
    Photo by Chris Ried on Unsplash

    2. Create a React Project with Vite

    Open a folder where you keep projects (for example ~/projects) and run:

    npm create vite@latest my-react-app -- --template react
    cd my-react-app
    npm install
    

    When prompted, Vite may ask for confirmation — accept the defaults. The react template gives you a minimal React 19 app with JSX and hot module replacement (HMR).

    Alternative templates:

    • react-ts — React + TypeScript (use when you are ready for types)
    • react-swc — same as react but uses SWC for faster compiles
    Terminal running npm commands for a React project
    Photo by Taiki Ishikawa on Unsplash

    3. Understand the Project Structure

    After scaffolding, your folder looks like this:

    my-react-app/
    ├── public/           # Static assets (favicon, etc.)
    ├── src/
    │   ├── App.jsx       # Root component
    │   ├── App.css       # Styles for App
    │   ├── main.jsx      # Entry point — mounts React to #root
    │   └── index.css     # Global styles
    ├── index.html        # Single HTML shell
    ├── package.json      # Dependencies and scripts
    └── vite.config.js    # Vite configuration
    

    Key files:

    • index.html — contains <div id="root"></div> where React attaches
    • src/main.jsx — calls createRoot(document.getElementById('root')).render(<App />)
    • src/App.jsx — your main UI component (edit this often while learning)

    4. Run the Development Server

    Start the local dev server:

    npm run dev
    

    Vite prints a local URL, typically http://localhost:5173. Open it in your browser. You should see the default Vite + React welcome page with a counter button.

    While the server runs, edit src/App.jsx — save the file and the browser updates instantly without a full reload. This HMR workflow is why Vite is preferred over older Create React App tooling.

    5. Your First Custom Component

    Replace the contents of src/App.jsx with a simple hello-world:

    function App() {
      return (
        <main style={{ fontFamily: 'system-ui', padding: '2rem' }}>
          <h1>Hello, React!</h1>
          <p>My first React app on Kindson The Genius.</p>
        </main>
      );
    }
    
    export default App;
    

    Save and confirm the page shows your heading. Congratulations — you have a working react setup vite project.

    6. VS Code Setup (Recommended)

    Visual Studio Code is a free editor well suited for React. Install these extensions:

    • ES7+ React/Redux/React-Native snippets — shortcuts for components
    • ESLint — catch common JavaScript mistakes
    • Prettier — consistent formatting (optional but helpful)

    Open your project folder with code . from the project directory. Use the integrated terminal (Ctrl+` or View → Terminal) to run npm run dev without leaving the editor.

    7. Build for Production

    When you are ready to deploy, create an optimized production build:

    npm run build
    npm run preview
    

    npm run build outputs static files to dist/. Host them on Netlify, Vercel, GitHub Pages, or any static file server. npm run preview serves the production build locally for testing.

    8. Common Setup Issues

    • Port 5173 in use — Vite picks the next free port; read the terminal output for the correct URL
    • Permission errors on npm — avoid sudo npm install; fix npm permissions or use nvm
    • Old Node version — upgrade to Node 20 LTS; React 19 expects modern JavaScript features
    • Blank page — check the browser console (F12) for syntax errors in JSX

    9. Next Steps

    Your environment is ready. Continue to Lesson 3 — React JSX and Components to learn how JSX works and how to split UI into reusable components.

    Back to Lesson 1 — React Introduction

    Frequently Asked Questions

    What do I need to install before learning React?
    Install Node.js 20 or newer and npm. Vite scaffolds a React project in one command.

    Should I use Vite or Create React App?
    Use Vite. It is faster, officially recommended for new React projects, and is the default toolchain in this tutorial series.

    Can I use yarn or pnpm instead of npm?
    Yes. Replace npm install with yarn or pnpm install if you prefer those package managers.


    Want live React or frontend classes? Join Alkademy for instructor-led React and JavaScript courses with hands-on projects.

  • React Tutorial — Introduction (2026)

    React Tutorial — Introduction (2026)

    Updated July 4, 2026. Refreshed for React 19 and current SEO best practices.

    React 19 Notes

    Modern React (19+) includes the React Compiler, improved Server Components, and the automatic JSX transform — you no longer need import React from 'react' in every file. React remains the foundation for Next.js, Remix, and React Native.

    Welcome to the React tutorial series on Kindson The Genius. In this first lesson you will learn what React is, why millions of developers choose it, and how this course is structured so you can go from zero to building real user interfaces with confidence.

    Prerequisites: Basic HTML and JavaScript familiarity helps but is not required — we explain concepts as we go. Estimated time: 35–45 minutes.

    1. What Is React?

    React is a JavaScript library for building user interfaces, maintained by Meta and a large open-source community. Instead of manipulating the DOM directly with imperative code, React lets you describe what the UI should look like for a given state — React handles updating the page efficiently.

    React is not a full framework like Angular. It focuses on the view layer: components, rendering, and client-side interactivity. You typically pair React with tools such as Vite (build tool), React Router (routing), and your choice of state management as your app grows.

    Key ideas you will use throughout this series:

    • Components — reusable pieces of UI (buttons, forms, pages)
    • JSX — HTML-like syntax inside JavaScript (Lesson 3)
    • Props — data passed into components
    • State — data that changes over time inside a component (later lessons)
    • Virtual DOM — React’s diffing engine for fast updates
    React developer building a web application
    Photo by James Harrison on Unsplash

    2. Why Learn React in 2026?

    React has remained one of the most popular frontend technologies for nearly a decade. Job boards, freelance projects, and enterprise codebases still list React as a core skill. Reasons to learn it today include:

    • Large ecosystem — UI libraries (Material UI, Chakra), data fetching (TanStack Query), testing (Vitest, React Testing Library)
    • React Native — reuse concepts for iOS and Android mobile apps
    • Meta-frameworks — Next.js, Remix, and Gatsby build on React for production sites
    • React 19 — improved performance, Server Components, and the React Compiler reduce boilerplate
    • Community — extensive documentation, tutorials, and Stack Overflow answers

    Whether you aim for frontend engineering, full-stack development, or mobile with React Native, this react tutorial gives you a solid foundation.

    Modern frontend development workspace
    Photo by Florian Olivo on Unsplash

    3. React vs Angular vs Vue

    All three are excellent choices. Here is a practical comparison for beginners:

    Aspect React Angular Vue
    Type Library (view layer) Full framework Progressive framework
    Language JavaScript / TypeScript TypeScript-first JavaScript / TypeScript
    Learning curve Moderate — learn JS + JSX first Steeper — modules, DI, RxJS Gentle — single-file components
    Flexibility High — you choose routing, state Opinionated — batteries included Balanced defaults
    Common use SPAs, Next.js sites, React Native Enterprise web apps SPAs, progressive adoption

    React’s flexibility is a strength: you learn transferable JavaScript skills and can adopt TypeScript, routing, and state libraries when you need them. If you also work with Angular, start with the Angular tutorial on this site, or see munonye.com for full-stack Spring Boot + Angular tutorials.

    4. What Can You Build with React?

    React powers interfaces of every scale:

    • Marketing sites and blogs — often via Next.js for SEO
    • Dashboards and admin panels — data tables, charts, forms
    • E-commerce storefronts — product grids, carts, checkout flows
    • Real-time apps — chat, notifications, collaborative tools
    • Mobile apps — React Native shares component thinking with web React

    In this series we start with a local development app and small components, then expand to state, lists, and forms in future lessons.

    5. React Tutorial Series Overview

    Follow these lessons in order. Each includes runnable code and SEO-friendly explanations:

    Lesson Topic Link
    1 Introduction (this lesson) You are here
    2 Setup — Node.js, Vite, first app React Setup with Vite
    3 JSX and Components React JSX and Components

    Later lessons (coming soon) will cover hooks, state, effects, routing, and fetching data from APIs.

    6. How React Renders a Page (High Level)

    When you run a React app, the browser loads JavaScript that calls createRoot on a DOM element (usually <div id="root">). React then renders your top-level component tree into that node. When state or props change, React computes a minimal set of DOM updates and applies them — you rarely call document.getElementById yourself.

    This declarative model reduces bugs: your UI is a function of data. If the data is wrong, fix the data or the component logic — the display stays in sync automatically.

    7. Next Steps

    You now know what React is and why it is worth learning. Continue to Lesson 2 — React Setup with Vite to install Node.js and create your first project.

    Frequently Asked Questions

    What is React used for?
    React is used to build interactive user interfaces for web, mobile, and desktop apps using reusable components and a declarative programming model.

    Is React still worth learning in 2026?
    Yes. React remains one of the most in-demand frontend skills, with strong ecosystem support, React Native for mobile, and modern features in React 19.

    Do I need to know TypeScript?
    No to start. This series uses JavaScript (.jsx). You can add TypeScript later for larger production codebases.


    New to React? Start with Lesson 1 — React Introduction.

    Want live React or frontend classes? Join Alkademy for instructor-led React and JavaScript courses with hands-on projects.