Jagmohan Krishan

Top-rated Plus on Upwork and recognized as a leading voice in website development on LinkedIn, I bring a passion for coding and a commitment to creating tailored solutions for my clients. Let’s turn your ideas into digital success together!

Getting Started with React

Whether you are taking your first steps into web development or transitioning from traditional vanilla JavaScript, React is one of the most powerful, popular, and rewarding tools you can learn today. Created and maintained by Meta alongside a vibrant open-source community, React powers everything from personal blogs to large-scale enterprise web applications like Netflix, Airbnb, and Facebook.

At first glance, React might seem intimidating with concepts like JSX, virtual DOM, components, and state management. However, once you grasp its fundamental principles, building modern, responsive, and dynamic user interfaces becomes intuitive and enjoyable. In this comprehensive beginner guide, we will break down the essential concepts of React step by step, set up a development environment, and build your first interactive component.


Why Choose React?

Before writing code, it helps to understand why React revolutionized frontend development. In traditional web development, manipulating the Document Object Model (DOM) directly using vanilla JavaScript often becomes messy and difficult to scale as your user interface grows complex. You frequently find yourself querying elements, listening for events, and manually rewriting HTML strings.

React changes this paradigm by introducing two game-changing ideas:

  • Component-Based Architecture: Instead of building monolithic HTML pages, you construct independent, reusable building blocks called components. Each component encapsulates its own structure, style, and logic.
  • Declarative UI: You simply declare what the user interface should look like based on the current data (state). When that data changes, React automatically figures out how to update the DOM efficiently without requiring manual intervention.

Prerequisites: What You Should Know First

To get the most out of React, you do not need to be an expert developer, but having a comfortable grasp of fundamental web technologies will make your learning journey significantly smoother:

  • HTML & CSS: Basic page structure, common tags, forms, and styling rules.
  • Modern JavaScript (ES6+):
    • Variable declarations (let and const)
    • Arrow functions (const greet = () => { ... })
    • Object and array destructuring (const { name } = user;)
    • Array methods such as .map() and .filter()
    • ES modules (import and export)

Core Concept 1: Components as Building Blocks

In React, user interfaces are composed entirely of components. Think of components like Lego bricks. You build small, simple components (like a button, an avatar, or a search input) and combine them to create larger components (like a navbar or card), eventually assembling an entire application.

In modern React, components are written as standard JavaScript functions that return markup. Here is the simplest possible React component:

function Welcome() {
  return <h1>Hello, Welcome to React!</h1>;
}

export default Welcome;

Notice that the function name begins with a capital letter (Welcome). In React, component names must always start with an uppercase letter to distinguish them from standard HTML tags like <div>, <h1>, or <button>.


Core Concept 2: Understanding JSX (JavaScript XML)

You probably noticed something unusual in the previous example: HTML tags written directly inside JavaScript! This syntax extension is known as JSX (JavaScript XML).

JSX is not HTML, though it looks nearly identical. Under the hood, JSX is compiled into standard JavaScript function calls (such as React.createElement). JSX gives you the full expressive power of JavaScript directly within your template syntax.

Key Rules of JSX:

  1. Return a Single Root Element: A component must return a single top-level element. If you have multiple sibling elements, wrap them in a parent container or an empty React Fragment (<> ... </>):
    function Profile() {
      return (
        <>
          <h2>Arjun Dev</h2>
          <p>Full-stack software engineer and tech enthusiast.</p>
        </>
      );
    }
    
  2. Close All Tags: Every tag must be explicitly closed, including self-closing tags like <img src="..." />, <input type="text" />, and <br />.
  3. camelCase Property Names: Because JSX is closer to JavaScript than HTML, reserved JavaScript words cannot be used as attribute names. For instance, use className instead of class, and htmlFor instead of for.
  4. Embed JavaScript Expressions in Curly Braces: You can execute any valid JavaScript expression inside JSX by wrapping it in curly braces { }:
    function CurrentYear() {
      const year = new Date().getFullYear();
      return <p>Current Year: {year}</p>;
    }
    

Core Concept 3: Passing Data with Props

Components are most useful when they can be reused with different data. In React, data is passed from a parent component down to a child component using props (short for properties).

Props behave like function arguments. They are read-only (immutable); a child component should never modify the props it receives.

function UserCard({ name, role, isAvailable }) {
  return (
    <div className="user-card">
      <h3>{name}</h3>
      <p>Role: {role}</p>
      <span>Status: {isAvailable ? "Available for hire" : "Busy"}</span>
    </div>
  );
}

// Using the component inside a parent:
function App() {
  return (
    <main>
      <UserCard name="Sarah Connor" role="Security Engineer" isAvailable={true} />
      <UserCard name="John Doe" role="UI Designer" isAvailable={false} />
    </main>
  );
}

By leveraging destructuring ({ name, role, isAvailable }), your component’s signature stays clean, readable, and self-documenting.


Core Concept 4: Managing State with the useState Hook

While props allow you to pass data into a component from the outside, state represents data that is private and managed entirely inside the component. Whenever state changes, React automatically re-renders the component to display the updated information.

To manage state in functional components, React provides a special function called a Hook: useState.

import { useState } from 'react';

function Counter() {
  // Declare a state variable named "count" initialized to 0
  const [count, setCount] = useState(0);

  function increment() {
    setCount(count + 1);
  }

  function decrement() {
    setCount(count - 1);
  }

  function reset() {
    setCount(0);
  }

  return (
    <div className="counter-container">
      <h2>Current Count: {count}</h2>
      <div className="button-group">
        <button onClick={decrement}>- Decrement</button>
        <button onClick={reset}>Reset</button>
        <button onClick={increment}>+ Increment</button>
      </div>
    </div>
  );
}

export default Counter;

Let’s analyze what happens here:

  • useState(0) declares a state variable with an initial value of 0.
  • It returns an array containing exactly two items: the current state value (count) and a setter function (setCount) used to update it.
  • When an event (like onClick) triggers setCount, React updates the internal value and re-renders the component with the new counter value.

Setting Up Your Modern React Development Environment

In modern web development, the recommended, blazing-fast tool for bootstrapping a new React project is Vite. Vite provides instant server start, lightning-fast Hot Module Replacement (HMR), and an optimized production build pipeline.

Step 1: Install Node.js

Ensure you have Node.js (version 18 or newer) installed on your machine. You can verify your installation by running in your terminal:

node -v
npm -v

Step 2: Create a New Vite Project

Run the following command in your terminal to initialize a project:

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

Step 3: Navigate and Install Dependencies

cd my-react-app
npm install

Step 4: Launch the Local Development Server

npm run dev

Open your browser and navigate to http://localhost:5173. You will see your live React starter template running immediately!


Building a Practical Mini-App: An Interactive Task Item

Let’s bring all these concepts together by creating a simple, practical interactive task checklist item that demonstrates components, props, state, and event handling.

import { useState } from 'react';

function TodoItem({ title, initialCompleted = false }) {
  const [completed, setCompleted] = useState(initialCompleted);

  const toggleStatus = () => {
    setCompleted(!completed);
  };

  return (
    <div style={{
      display: 'flex',
      alignItems: 'center',
      gap: '12px',
      padding: '10px 16px',
      margin: '8px 0',
      borderRadius: '8px',
      backgroundColor: completed ? '#e8f5e9' : '#f5f5f5',
      border: '1px solid #ddd'
    }}>
      <input
        type="checkbox"
        checked={completed}
        onChange={toggleStatus}
        style={{ cursor: 'pointer', transform: 'scale(1.3)' }}
      />
      <span style={{
        textDecoration: completed ? 'line-through' : 'none',
        color: completed ? '#666' : '#222',
        fontSize: '1.1rem',
        fontWeight: completed ? 'normal' : '500'
      }}>
        {title}
      </span>
      <span style={{ marginLeft: 'auto', fontSize: '0.85rem', color: '#888' }}>
        {completed ? "Done" : "Pending"}
      </span>
    </div>
  );
}

export default function App() {
  const tasks = [
    { id: 1, title: "Install Node.js & Vite", done: true },
    { id: 2, title: "Learn React Components & JSX", done: true },
    { id: 3, title: "Master Props and useState Hook", done: false },
    { id: 4, title: "Build your first full-stack application", done: false }
  ];

  return (
    <div style={{ maxWidth: '480px', margin: '40px auto', fontFamily: 'system-ui, sans-serif' }}>
      <h1>My React Learning Checklist</h1>
      {tasks.map((task) => (
        <TodoItem key={task.id} title={task.title} initialCompleted={task.done} />
      ))}
    </div>
  );
}

In this example:

  • The parent App component iterates through an array of tasks using JavaScript’s .map() method.
  • Each item receives a unique key prop (mandatory for performance optimization in React lists).
  • The child TodoItem component manages its own internal completed state independently, responding to user clicks dynamically.

Essential Best Practices & Pitfalls to Avoid

  • Never mutate state directly: Always use the setter function provided by useState. Avoid writing count = count + 1. Direct mutation prevents React from detecting changes and triggering re-renders.
  • Always use the key prop in lists: When rendering collections of items with .map(), always supply a stable, unique identifier as the key so React can track item insertions, deletions, and reorders efficiently.
  • Keep components focused: Follow the Single Responsibility Principle. If a component grows too large or handles too many duties, break it down into smaller sub-components.
  • Keep state as close to where it is needed as possible: Avoid pushing state into a global store or a high-level parent component until multiple components genuinely need access to it.

Where to Go From Here

Congratulations! You now understand the core foundations that power every single React application: Components, JSX, Props, and State. As you continue your web development journey, here are the next topics to explore:

  1. The useEffect Hook: For managing side effects such as data fetching from REST or GraphQL APIs, subscribing to services, and interacting with timers.
  2. Client-Side Routing: Using libraries like React Router to build multi-page single-page applications (SPAs).
  3. Full-Stack Frameworks: Once you are confident with core React, frameworks like Next.js and Remix offer server-side rendering (SSR), static site generation (SSG), and built-in routing for production-ready applications.

The best way to solidify your skills is to build real projects. Start small—create a calculator, a weather widget, or an expense tracker—and experiment with how components communicate. Happy coding!

Share this

Greetings! I'm Jagmohan Krishan, a seasoned website designer and developer based in Chandigarh, India. My expertise encompasses a spectrum of technologies, including SQL, Next.js, Node.js, React.js, MongoDB, Postgres, MySQL, Django, Ant Design, Tailwind, along with a robust skill set in teamwork, problem-solving, and proficiency in version control systems like Git, GitHub, and Bitbucket.