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.
This guide introduces React from the beginning, including JSX, components, props, state, Hooks, events, forms, API requests, routing, and projects.
Table of Contents
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.
- Build reusable components.
- Update interfaces when data changes.
- Organize large interfaces into smaller pieces.
- Work with backend APIs.
- Use a large ecosystem of development tools.
- Build interactive web applications.
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.
| JavaScript | React |
|---|---|
| A programming language | A JavaScript library |
| Can be used for many kinds of applications | Focuses on user interfaces |
| Provides language features | Provides 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.
function Welcome() {
return <h1>Hello, TechLearn Hub!</h1>;
}
export default Welcome;
The component can be used in another component like this:
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.
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.
function Card() {
return (
<div className="card">
Hello
</div>
);
}
JavaScript Inside JSX
Use curly braces to include JavaScript expressions in JSX.
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.
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.
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.
function Button() {
function handleClick() {
alert("Button clicked!");
}
return (
<button type="button" onClick={handleClick}>
Click Me
</button>
);
}
Common React event props include:
onClick— a click action.onChange— a form value changes.onSubmit— a form is submitted.onFocus— an element receives focus.onBlur— an element loses focus.onMouseEnter— the pointer enters an element.
8. Conditional Rendering
Conditional rendering means showing different content depending on a condition. You can use regular JavaScript conditions or expressions in JSX.
function LoginMessage({ loggedIn }) {
if (loggedIn) {
return <h2>Welcome back!</h2>;
}
return <h2>Please log in.</h2>;
}
You can also use a conditional 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.
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.
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.
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.
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;
/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.
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.
| Method | Typical purpose | Example |
|---|---|---|
GET | Retrieve data | /api/products |
POST | Create a resource or submit data | /api/products |
PUT | Replace a resource | /api/products/1 |
PATCH | Update part of a resource | /api/products/1 |
DELETE | Delete 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.
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:
App
|
+-- Header
+-- Navigation
+-- ProductList
| +-- ProductCard
| +-- ProductCard
| +-- ProductCard
+-- Footer
17. Common React Hooks
| Hook | Common purpose |
|---|---|
useState | Store component state |
useEffect | Synchronize with external systems |
useContext | Read a value from context |
useReducer | Manage state with a reducer function |
useMemo | Cache a calculated value between renders when appropriate |
useCallback | Cache a function definition between renders when appropriate |
useRef | Keep 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
- Call Hooks at the top level of function components or custom Hooks.
- Do not call Hooks inside loops, conditions, or nested functions.
- Use the same Hooks in the same order on every render.
- Follow the current React documentation for each Hook.
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:
- Regular CSS files.
- CSS Modules.
- Inline styles for appropriate use cases.
- Utility-first CSS frameworks.
- Reusable component libraries.
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.
- Use semantic HTML elements.
- Associate form inputs with labels.
- Use clear text for buttons and links.
- Add appropriate alternative text to meaningful images.
- Support keyboard navigation.
- Maintain readable text and sufficient color contrast.
- Display useful error messages for forms.
22. React Security
Security matters in every web application, including React projects.
- Validate and authorize important actions on the server.
- Do not rely on client-side validation alone.
- Never put private server credentials in frontend code.
- Use appropriate authentication and access controls.
- Keep dependencies updated.
- Be careful when rendering untrusted HTML.
- Use HTTPS for production websites.
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.
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
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
- Create the project.
- Build small reusable components.
- Add styles and layout.
- Manage state and events.
- Connect to APIs when needed.
- Handle loading, error, and empty states.
- Test the application.
- Fix accessibility and security problems.
- Create a production build.
- Deploy the application to a suitable host.
25. React vs Traditional JavaScript
| Traditional JavaScript | React |
|---|---|
| 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
| React | Angular |
|---|---|
| A JavaScript library for user interfaces | A broader frontend framework |
| Flexible ecosystem choices | Provides more integrated conventions and tools |
| JSX is commonly used | HTML templates and TypeScript are commonly used |
27. React vs Vue
| React | Vue |
|---|---|
| A JavaScript UI library | A progressive JavaScript framework |
| JSX is common, though other approaches exist | Single-file components are common |
| Offers a large ecosystem of libraries | Offers its own ecosystem and conventions |
28. What Can You Build With React?
- Business websites.
- Dashboards and admin panels.
- Online stores.
- Education platforms.
- Booking applications.
- Social application interfaces.
- Productivity tools.
- Blogs and content websites.
- Single-page applications.
- Interactive data interfaces.
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
- Making components unnecessarily large.
- Modifying props directly.
- Using unstable keys in lists.
- Creating state that can be calculated from existing values.
- Ignoring API loading and error states.
- Calling Hooks inside conditions or loops.
- Putting private credentials in frontend code.
- Ignoring accessibility.
- Installing unnecessary dependencies.
- Skipping testing and debugging.
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.
- Counter: practice state and button events.
- To-do list: add, complete, and remove tasks.
- Calculator: handle inputs and arithmetic.
- Notes application: practice forms and lists.
- Weather interface: practice API requests and loading states.
- Product catalog: practice props and reusable cards.
- Movie search interface: practice search input and API results.
- Dashboard: organize several components and data displays.
Intermediate Project Ideas
- Task management application.
- Online store frontend.
- Learning platform interface.
- Real-time chat interface.
- Blog with multiple views.
- Admin dashboard.
- Social media interface.
32. React Learning Path
- Learn HTML fundamentals.
- Learn CSS and responsive layouts.
- Learn JavaScript variables, arrays, objects, and functions.
- Understand modern JavaScript features.
- Learn React components and JSX.
- Practice props and state.
- Learn events and conditional rendering.
- Learn lists and forms.
- Understand Hooks.
- Learn API requests and error handling.
- Explore routing.
- Practice testing, accessibility, and security.
- Build and deploy real projects.
33. React Cheat Sheet
| Concept | Purpose |
|---|---|
| Component | Reusable part of the interface |
| JSX | HTML-like syntax inside JavaScript |
| Props | Pass data to components |
| State | Remember changing component data |
useState | Declare state in a function component |
useEffect | Synchronize with external systems |
onClick | Respond to click events |
map() | Transform array items into rendered elements |
| Router | Connect URLs to application views |
| API | Communicate 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.