TechLearn Hub

Learn Technology in Simple English

What Is React? A Beginner's Guide

React is a JavaScript library used to build user interfaces, especially interactive websites and web applications. It helps developers organize interfaces into reusable components.

React was originally developed at Facebook and is maintained by Meta and the open-source community.

Simple explanation: React helps developers build interfaces using reusable components instead of managing every part of a large interface as one block of code.

This guide introduces React from the beginning, including JSX, components, props, state, Hooks, events, forms, API requests, routing, and projects.

1. Why Is React Important?

Modern websites may contain menus, forms, dashboards, product lists, and many other interactive elements. React offers a component-based approach to organizing those interfaces.

2. React Is a JavaScript Library

React is not a separate programming language. It is a JavaScript library used mainly to build user interfaces. JavaScript knowledge is important because React applications use JavaScript or TypeScript.

JavaScriptReact
A programming languageA JavaScript library
Can be used for many kinds of applicationsFocuses on user interfaces
Provides language featuresProvides patterns for building interfaces

3. What Is a React Component?

A component is a reusable part of an interface. Common examples include headers, navigation menus, buttons, cards, login forms, product lists, and footers.

React function components are JavaScript functions that return React elements, often written using JSX.

React — First component
function Welcome() {
  return <h1>Hello, TechLearn Hub!</h1>;
}

export default Welcome;

The component can be used in another component like this:

React — Use a component
function App() {
  return (
    <main>
      <Welcome />
    </main>
  );
}

export default App;

4. What Is JSX?

JSX is a syntax commonly used with React. It allows developers to write HTML-like markup inside JavaScript code. JSX is transformed into JavaScript that React can use.

React — JSX example
function Welcome() {
  return (
    <div>
      <h1>Welcome</h1>
      <p>Learn React with TechLearn Hub.</p>
    </div>
  );
}

JSX Is Similar to HTML, but Different

JSX follows some rules that differ from HTML. For example, React commonly uses className instead of class. Components that return multiple sibling elements usually wrap them in a parent element or a Fragment.

React — className
function Card() {
  return (
    <div className="card">
      Hello
    </div>
  );
}

JavaScript Inside JSX

Use curly braces to include JavaScript expressions in JSX.

React — Expressions
const name = "Student";

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

5. Props

Props allow a parent component to pass data to a child component. They help make components reusable with different information.

React — Receive props
function Welcome({ name }) {
  return <h1>Hello, {name}!</h1>;
}

function App() {
  return (
    <div>
      <Welcome name="Amina" />
      <Welcome name="Abdullahi" />
    </div>
  );
}

The same Welcome component displays different greetings because it receives different props. Treat props as read-only values; do not modify them directly.

6. State and useState

State is data that a component remembers between renders. When state changes through its setter function, React can render the component again to display the updated value.

The useState Hook provides a state value and a function to update it.

React — Counter with useState
import { useState } from "react";

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>Count: {count}</p>

      <button onClick={() => setCount(c => c + 1)}>
        Increase
      </button>
    </div>
  );
}

export default Counter;

In this example, count stores the current number. The setCount function updates it when the button is clicked. The callback form is useful when the next value depends on the previous one.

7. React Events

React can respond to actions such as clicks, typing, form submissions, and focus changes. Event handlers are usually passed as functions.

React — Click event
function Button() {
  function handleClick() {
    alert("Button clicked!");
  }

  return (
    <button type="button" onClick={handleClick}>
      Click Me
    </button>
  );
}

Common React event props include:

8. Conditional Rendering

Conditional rendering means showing different content depending on a condition. You can use regular JavaScript conditions or expressions in JSX.

React — Conditional message
function LoginMessage({ loggedIn }) {
  if (loggedIn) {
    return <h2>Welcome back!</h2>;
  }

  return <h2>Please log in.</h2>;
}

You can also use a conditional expression:

React — Ternary expression
function Status({ online }) {
  return (
    <p>
      {online ? "Online" : "Offline"}
    </p>
  );
}

9. Rendering Lists

JavaScript's map() method can transform an array into a list of React elements. Give each item a stable key that is unique among its siblings.

React — Render a list
const names = ["Amina", "Ali", "John"];

function Names() {
  return (
    <ul>
      {names.map((name) => (
        <li key={name}>{name}</li>
      ))}
    </ul>
  );
}

Keys help React identify list items when they are added, removed, or reordered. If list values can repeat, use a stable unique identifier from your data instead of the value alone.

10. Forms in React

React can manage form input, validation, and submission. A controlled input uses state to determine its current value.

React — Controlled form
import { useState } from "react";

function EmailForm() {
  const [email, setEmail] = useState("");

  function handleSubmit(event) {
    event.preventDefault();
    alert("Submitted: " + email);
  }

  return (
    <form onSubmit={handleSubmit}>
      <label htmlFor="email">Email address</label>

      <input
        id="email"
        type="email"
        value={email}
        onChange={(event) => setEmail(event.target.value)}
        required
      />

      <button type="submit">Submit</button>
    </form>
  );
}

export default EmailForm;

The preventDefault() call prevents the browser's default form submission behavior. This example demonstrates input handling only; a real application should send the data to an appropriate backend if necessary.

11. The useEffect Hook

The useEffect Hook is used to synchronize a component with external systems, such as browser APIs, subscriptions, timers, or network connections. It is not required for every calculation or event handler.

React — useEffect example
import { useEffect } from "react";

function App() {
  useEffect(() => {
    document.title = "React Tutorial";
  }, []);

  return <h1>Hello, React!</h1>;
}

export default App;

The empty dependency array means this Effect is set up when the component mounts, with development behavior potentially including an extra setup and cleanup cycle under Strict Mode. Effects should include appropriate cleanup when they create subscriptions or other resources that need to be released.

12. Fetching Data From an API

React applications often request information from backend APIs. The following example uses fetch() inside an Effect and handles loading, success, and error states.

React — API request
import { useEffect, useState } from "react";

function Users() {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  useEffect(() => {
    const controller = new AbortController();

    async function loadUsers() {
      try {
        const response = await fetch("/api/users", {
          signal: controller.signal
        });

        if (!response.ok) {
          throw new Error("Could not load users");
        }

        const data = await response.json();
        setUsers(data);
      } catch (err) {
        if (err.name !== "AbortError") {
          setError(err.message);
        }
      } finally {
        if (!controller.signal.aborted) {
          setLoading(false);
        }
      }
    }

    loadUsers();

    return () => controller.abort();
  }, []);

  if (loading) return <p>Loading users...</p>;
  if (error) return <p>Error: {error}</p>;

  return (
    <ul>
      {users.map(user => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );
}

export default Users;
Note: /api/users is an example endpoint, not a built-in React service. Replace it with an API that exists in your project and returns data in the expected format.

13. React and Node.js

React and Node.js are often used in the same application, but they have different roles. React manages the user interface, while a Node.js backend can provide APIs, authentication, and database access.

Application architecture
React Frontend
      |
      | HTTP Request
      v
Backend API
      |
      v
Database

React can also work with backends built using other technologies. The frontend and backend communicate through defined interfaces, often HTTP APIs.

14. REST APIs and HTTP Methods

A REST-style API often uses HTTP methods to describe actions on resources. The actual behavior depends on the API design.

MethodTypical purposeExample
GETRetrieve data/api/products
POSTCreate a resource or submit data/api/products
PUTReplace a resource/api/products/1
PATCHUpdate part of a resource/api/products/1
DELETEDelete a resource/api/products/1

15. React Router

React Router is a popular library for adding navigation to React applications. It can connect URLs to different views, such as Home, About, Products, Profile, and Settings.

For installation and current setup instructions, see the official React Router documentation.

Routing is particularly useful when an application has multiple pages or views and users need to navigate between them without treating each view as an unrelated application.

16. Component Reusability and Composition

A reusable component can receive props to display different content. Components can also be combined to create larger interfaces.

React — Product card
function ProductCard({ name, price }) {
  return (
    <article>
      <h3>{name}</h3>
      <p>Price: ${price}</p>
    </article>
  );
}

function Products() {
  return (
    <section>
      <ProductCard name="Notebook" price={5} />
      <ProductCard name="Pen" price={2} />
    </section>
  );
}

A larger interface might be organized like this:

Component structure
App
 |
 +-- Header
 +-- Navigation
 +-- ProductList
 |     +-- ProductCard
 |     +-- ProductCard
 |     +-- ProductCard
 +-- Footer

17. Common React Hooks

HookCommon purpose
useStateStore component state
useEffectSynchronize with external systems
useContextRead a value from context
useReducerManage state with a reducer function
useMemoCache a calculated value between renders when appropriate
useCallbackCache a function definition between renders when appropriate
useRefKeep a mutable reference between renders

useContext

Context can make shared values available to components without passing props through every intermediate level. Common examples include theme preferences, language settings, and selected application-wide information.

useRef

A ref can hold a value between renders without triggering a render when the value changes. Refs can also point to DOM elements, such as an input that needs to receive focus.

Rules of Hooks

18. State Management

Small applications may only need React's built-in state tools. As an application grows, you may consider Context, reducers, or additional state-management libraries.

Choose a solution based on the complexity of the state and the needs of the application. Adding more libraries does not automatically make an application better.

19. React and TypeScript

TypeScript adds static type checking to JavaScript. It is commonly used with React to help describe component props, event values, and data structures. Types can catch some mistakes during development and make large projects easier to maintain.

20. Styling React Applications

React does not require one specific styling system. Common choices include:

Choose a styling approach that suits the size, design, and maintenance needs of your project.

21. React and Accessibility

Accessible interfaces help people use an application with different devices, assistive technologies, and interaction methods.

22. React Security

Security matters in every web application, including React projects.

Important: Anything included in frontend JavaScript can potentially be inspected by users. Keep private API keys, database passwords, and server secrets on a properly secured backend.

23. React Developer Tools

React Developer Tools is a browser extension that helps developers inspect React component trees and state. Standard browser developer tools are also useful for examining network requests, console errors, HTML, storage, and performance.

24. Creating a React Project

React applications can be created with different tools. Vite is one popular build tool for creating a frontend project.

Terminal — Create a project
npm create vite@latest

Follow the prompts to choose a project name and framework. For a React project, select React and then choose JavaScript or TypeScript as needed. The exact prompts can change with newer versions of the tool.

You can find current instructions in the official Vite guide and the official React learning documentation.

Example Project Structure

Project files
my-react-app/
|
+-- src/
|   +-- components/
|   +-- App.jsx
|   +-- main.jsx
|
+-- public/
+-- package.json
+-- index.html

Your exact folder structure depends on the selected tool and project setup.

Typical Development Workflow

  1. Create the project.
  2. Build small reusable components.
  3. Add styles and layout.
  4. Manage state and events.
  5. Connect to APIs when needed.
  6. Handle loading, error, and empty states.
  7. Test the application.
  8. Fix accessibility and security problems.
  9. Create a production build.
  10. Deploy the application to a suitable host.

25. React vs Traditional JavaScript

Traditional JavaScriptReact
You may update DOM elements directly.React manages UI updates through its rendering model.
Organization depends on your chosen design.Encourages component-based organization.
Can be used without a UI library.Provides a structured approach to building interfaces.

26. React vs Angular

ReactAngular
A JavaScript library for user interfacesA broader frontend framework
Flexible ecosystem choicesProvides more integrated conventions and tools
JSX is commonly usedHTML templates and TypeScript are commonly used

27. React vs Vue

ReactVue
A JavaScript UI libraryA progressive JavaScript framework
JSX is common, though other approaches existSingle-file components are common
Offers a large ecosystem of librariesOffers its own ecosystem and conventions

28. What Can You Build With React?

29. React for Mobile Development

React is mainly associated with web user interfaces. React Native is a separate technology that uses React concepts to build mobile applications. It allows developers to work with JavaScript or TypeScript while using native platform components.

Learn more from the official React Native website.

30. Common React Mistakes

31. Beginner React Projects

Practice the fundamentals by building small applications. Start with one feature at a time, then gradually combine components, state, and events.

Intermediate Project Ideas

32. React Learning Path

  1. Learn HTML fundamentals.
  2. Learn CSS and responsive layouts.
  3. Learn JavaScript variables, arrays, objects, and functions.
  4. Understand modern JavaScript features.
  5. Learn React components and JSX.
  6. Practice props and state.
  7. Learn events and conditional rendering.
  8. Learn lists and forms.
  9. Understand Hooks.
  10. Learn API requests and error handling.
  11. Explore routing.
  12. Practice testing, accessibility, and security.
  13. Build and deploy real projects.

33. React Cheat Sheet

ConceptPurpose
ComponentReusable part of the interface
JSXHTML-like syntax inside JavaScript
PropsPass data to components
StateRemember changing component data
useStateDeclare state in a function component
useEffectSynchronize with external systems
onClickRespond to click events
map()Transform array items into rendered elements
RouterConnect URLs to application views
APICommunicate with backend services

34. Frequently Asked Questions

Is React a programming language?

No. React is a JavaScript library used to build user interfaces.

Should I learn JavaScript before React?

Yes. Understanding JavaScript variables, functions, arrays, objects, and modern syntax makes React much easier to learn.

Can React build websites?

Yes. React is widely used to build interactive websites and web applications.

Can React connect to an API?

Yes. React applications can request data from backend APIs using JavaScript tools such as fetch().

Can React work with Node.js?

Yes. React can provide the frontend while Node.js provides backend services. They communicate through APIs or other suitable interfaces.

Can I use React with TypeScript?

Yes. React and TypeScript are commonly used together.

Is React free?

React is available as open-source software.

Can React be used to make mobile applications?

React Native is a separate technology that uses React concepts to build mobile applications.

How long does it take to learn React?

It depends on your JavaScript knowledge, practice time, and project goals. Start with small components and build progressively more complete projects.

Conclusion

React is a widely used JavaScript library for building interactive user interfaces. Its component-based approach helps developers organize reusable parts of a website or application.

Start by learning HTML, CSS, and JavaScript. Then practice React components, JSX, props, state, Hooks, forms, API requests, and routing. Small practical projects will help you understand how these concepts work together.

Your next step: Build a simple counter or to-do list, then extend it with reusable components, form handling, and persistent data.

Back to top ↑