Top News

React Tags: Complete Guide with Code & Explanation

Complete Guide to React: Components, Hooks, and Examples

React is one of the most popular JavaScript libraries used to build modern frontend applications. It enables developers to create dynamic, fast, and scalable web apps using reusable components.

In this article, we will explore all key React concepts, their usage, and examples to help you master React.


📌 What is React?

React is a JavaScript library for building user interfaces (UI). It was developed by Facebook (Meta) and is widely used for building single-page applications (SPAs).

🔹 Why Use React?
Component-based architecture (Reusable UI components).
Fast rendering with the Virtual DOM.
State management for interactive UIs.
Rich ecosystem (Hooks, Context API, Next.js support).

🔹 Basic React Example:

import React from "react";

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

export default App;

✅ This is a simple React functional component rendering "Hello, React!".


📌 How to Use React?

1️⃣ Add React to an HTML File (CDN Method)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>React App</title>
</head>
<body>
    <div id="root"></div>

    <script src="https://unpkg.com/react@18/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
    <script>
      ReactDOM.createRoot(document.getElementById("root")).render(
        React.createElement("h1", null, "Hello, React!")
      );
    </script>
</body>
</html>

Use: Quickly test React without setting up a full project.


2️⃣ Create a React App (Recommended)

Use Create React App for faster development:

npx create-react-app my-app
cd my-app
npm start

Use: Sets up a full React project with Babel, Webpack, and JSX support.


📌 React Components (Building Blocks of React)

Component Type Description
Functional Component Uses function syntax, recommended in modern React.
Class Component Uses class syntax, used before Hooks.

1️⃣ Functional Component (Recommended)

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

2️⃣ Class Component (Old Approach)

import React, { Component } from "react";

class Greeting extends Component {
  render() {
    return <h2>Hello, Welcome to React!</h2>;
  }
}

Use: Functional components are preferred due to React Hooks.


📌 JSX (JavaScript XML)

JSX allows us to write HTML inside JavaScript.

const element = <h1>Hello, JSX!</h1>;

JSX Benefits:

  • Easier to read and write.
  • Converts into JavaScript using Babel.

🔹 Without JSX:

React.createElement("h1", null, "Hello, JSX!");

JSX is preferred because it makes React code more readable.


📌 React Props (Passing Data to Components)

Props (short for properties) allow passing data between components.

🔹 Example of Props Usage:

function Welcome(props) {
    return <h1>Hello, {props.name}!</h1>;
  }
 
  function App() {
    return <Welcome name="John" />;
  }

Use: Props make components dynamic by allowing them to receive data from parents.


📌 React State (Managing Component Data)

State allows components to manage dynamic data.

1️⃣ Using useState Hook (Modern Approach)

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>
  );
}

Use: useState allows functional components to handle dynamic data.


📌 React Events (Handling User Actions)

function ClickButton() {
    function handleClick() {
      alert("Button Clicked!");
    }
 
    return <button onClick={handleClick}>Click Me</button>;
  }

Use: Adds interactivity to React components.


📌 React Hooks (Powerful Features in Functional Components)

Hooks let you use state and lifecycle features inside functional components.

1️⃣ Common React Hooks

Hook Description
useState Manages state inside functional components
useEffect Runs side effects (API calls, event listeners)
useContext Manages global state without Redux
useRef Accesses DOM elements directly
useMemo Optimizes performance by memoizing calculations

2️⃣ Example of useEffect Hook (Fetching API Data)

import { useState, useEffect } from "react";

function DataFetcher() {
  const [data, setData] = useState([]);

  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/posts")
      .then(response => response.json())
      .then(data => setData(data));
  }, []);

  return <ul>{data.map(post => <li key={post.id}>{post.title}</li>)}</ul>;
}

Use: Fetches API data when the component loads.


📌 React Router (Navigation Between Pages)

Install React Router:

npm install react-router-dom

🔹 Example:

import { BrowserRouter, Routes, Route } from "react-router-dom";
import Home from "./Home";
import About from "./About";

function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
      </Routes>
    </BrowserRouter>
  );
}

Use: Enables multi-page navigation in React apps.


📊 React Cheat Sheet

Concept Example
JSX <h1>Hello, JSX!</h1>
Functional Component function App() { return <h1>Hi</h1>; }
Props <Welcome name="John" />
State const [count, setCount] = useState(0);
Event <button onClick={handleClick}>Click</button>
useEffect useEffect(() => {...}, []);
Router <Route path="/" element={<Home />} />

🖼️ React Infographic

Here’s an infographic summarizing key React concepts:

React Infographic


🚀 Conclusion: Why Use React?

React is essential for modern web development because it:
Simplifies UI development.
Improves performance with the Virtual DOM.
Supports reusable components.



Post a Comment

Previous Post Next Post