Skip to content
Youths Forum Youths Forum Youths Forum

Tech Blogs & Programming Tutorials

Youths Forum Youths Forum Youths Forum

Tech Blogs & Programming Tutorials

  • Blog
  • News
  • Programming
    • PHP
    • JavaScript
    • JQuery
    • CSS
    • HTML
    • API
  • Stock Market Live
  • Automobiles
    • Cars
  • Gadgets
    • Phones
    • Android Phones

Categories

  • Automobiles (12)
    • Cars (7)
  • Blog (103)
    • Poems (2)
    • Space (2)
  • Command (2)
  • Education (2)
  • Entertainment (4)
  • Gadgets (9)
    • Phones (8)
      • Android Phones (4)
  • HTML Templates (11)
  • IT Training Institutes (1)
  • Lifestyle (4)
  • News (51)
  • Others (23)
  • Programming (296)
    • API (16)
    • CSS (83)
    • Database (4)
    • Hosting (1)
    • HTML (37)
    • JavaScript (117)
      • JQuery (27)
      • ReactJS (7)
    • PHP (116)
  • Python (3)
  • recipes (1)
  • SEE Result (1)
  • Server (3)
  • Blog
  • News
  • Programming
    • PHP
    • JavaScript
    • JQuery
    • CSS
    • HTML
    • API
  • Stock Market Live
  • Automobiles
    • Cars
  • Gadgets
    • Phones
    • Android Phones
Close

Search

ReactJSProgramming

Ultimate Guide to React, React Hooks, and React Router v6

By Admin
March 15, 2025 3 Min Read
0

Introduction to React

React is a popular JavaScript library for building user interfaces, particularly for single-page applications where you need a fast and interactive UI. Developed by Facebook, React enables developers to create reusable UI components and manage state efficiently.

React allows developers to build scalable applications by utilizing components, state management, and an efficient virtual DOM. It follows a declarative approach, making the UI more predictable and easier to debug. By leveraging React Hooks, developers can efficiently manage state and lifecycle events without needing class components.

Setting Up a React Project

To get started with React, you need Node.js installed on your system. You can create a new React project using:

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

This command sets up a new React application with all the necessary configurations, including Webpack, Babel, and development dependencies.

React Components

React applications are built using components. There are two main types:

  • Functional Components (Stateless)
  • Class Components (Stateful – rarely used in modern React)

Functional Component Example:

function Greeting() {
  return <h1>Hello, World!</h1>;
}
export default Greeting;

Class Component Example:

import React, { Component } from 'react';

class Greeting extends Component {
  render() {
    return <h1>Hello, World!</h1>;
  }
}
export default Greeting;

In modern React development, functional components are preferred because they are simpler and support hooks for managing state and side effects.

JSX: JavaScript XML

JSX is a syntax extension for JavaScript that allows writing HTML-like code inside JavaScript. JSX makes React code more readable and expressive.

const element = <h1>Welcome to React</h1>;

JSX must be transpiled using Babel before the browser can understand it.

React Hooks

React Hooks allow functional components to have state and other React features. Let’s go through some important hooks.

useState Hook

The useState hook is used to manage state in functional components.

import React, { 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;

useEffect Hook

The useEffect hook allows performing side effects in function components.

import React, { useState, useEffect } from 'react';

function Timer() {
  const [seconds, setSeconds] = useState(0);
  
  useEffect(() => {
    const interval = setInterval(() => {
      setSeconds(prevSeconds => prevSeconds + 1);
    }, 1000);
    return () => clearInterval(interval);
  }, []);
  
  return <p>Timer: {seconds}s</p>;
}
export default Timer;

useContext Hook

The useContext hook provides a way to share values like themes and authentication status between components.

import React, { useContext, createContext } from 'react';

const ThemeContext = createContext('light');

function ThemedComponent() {
  const theme = useContext(ThemeContext);
  return <p>Current Theme: {theme}</p>;
}

function App() {
  return (
    <ThemeContext.Provider value="dark">
      <ThemedComponent />
    </ThemeContext.Provider>
  );
}
export default App;

useRef Hook

The useRef hook is used to reference DOM elements directly.

import React, { useRef } from 'react';

function FocusInput() {
  const inputRef = useRef();
  
  const focusInput = () => {
    inputRef.current.focus();
  };
  
  return (
    <div>
      <input ref={inputRef} type="text" />
      <button onClick={focusInput}>Focus Input</button>
    </div>
  );
}
export default FocusInput;

useMemo Hook

The useMemo hook optimizes performance by memoizing expensive calculations.

import React, { useState, useMemo } from 'react';

function ExpensiveCalculation({ num }) {
  const result = useMemo(() => {
    console.log('Calculating...');
    return num * 2;
  }, [num]);
  
  return <p>Result: {result}</p>;
}

function App() {
  const [num, setNum] = useState(0);
  return (
    <div>
      <button onClick={() => setNum(num + 1)}>Increase</button>
      <ExpensiveCalculation num={num} />
    </div>
  );
}
export default App;

React Router v6

React Router is used for handling navigation in React applications. To install it, run:

npm install react-router-dom

Basic Setup

import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom';

function Home() {
  return <h1>Home Page</h1>;
}

function About() {
  return <h1>About Page</h1>;
}

function App() {
  return (
    <Router>
      <nav>
        <Link to="/">Home</Link>
        <Link to="/about">About</Link>
      </nav>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
      </Routes>
    </Router>
  );
}
export default App;

useLocation Hook

The useLocation hook returns the current location object.

import { useLocation } from 'react-router-dom';

function ShowLocation() {
  const location = useLocation();
  return <p>Current Path: {location.pathname}</p>;
}
export default ShowLocation;

useParams Hook

The useParams hook retrieves URL parameters.

import { useParams } from 'react-router-dom';

function UserProfile() {
  const { id } = useParams();
  return <h1>User ID: {id}</h1>;
}

Passing State via Link

import { Link, useLocation } from 'react-router-dom';

function Home() {
  return <Link to="/details" state={{ name: 'John Doe' }}>Go to Details</Link>;
}

function Details() {
  const location = useLocation();
  return <h1>{location.state?.name || 'No Data'}</h1>;
}

React is a powerful library that enables developers to build interactive and efficient web applications. By mastering React Hooks and React Router, you can create scalable, maintainable applications with ease.

Tags:

reactjs
Author

Admin

Follow Me
Other Articles
Previous

Creating a Read More Design with Pure CSS

Next

System Information, Geolocation and Battery Monitoring using JavaScript

FIFA World Cup 2026 Predict and Win by SportsGuff

Recent Posts

  • Unpacking Nepal’s Record Rs 2.12 Trillion Budget and What It Means for You
  • How to Write a Strong Scholarship Application: The Ultimate Step-by-Step Guide
  • How to Prepare for Exams Without Stress: The Ultimate Science-Backed Guide
  • Chiranjibi Adhikari Appointed Acting President of CAN Federation
  • How to Design a Student Marksheet Using HTML and CSS

Tags

adsense ai animate animation animation using HTML and CSS API blog calculator chatgpt Cryptocurrency CSS css animation design Email Facebook featured filemanager file manager free template google htaccess HTML image Instagram interview javascript JQuery jquery ui NADA AutoShow NADA Auto Show 2024 password PHP Progressive Web App PWA QR random react reactjs Rotate travel Twitter vpn youthforum youthsforum youtube

About Us

At Youths Forum, we are passionate about sharing knowledge that empowers students, educators, professionals, and technology enthusiasts.

Our Mission

Our mission is simple: to make technology and education accessible, understandable, and beneficial for everyone. We strive to create content that helps our readers learn new skills and stay updated with industry developments.

RSS RSS

  • Unpacking Nepal’s Record Rs 2.12 Trillion Budget and What It Means for You Admin
  • How to Write a Strong Scholarship Application: The Ultimate Step-by-Step Guide Admin
  • How to Prepare for Exams Without Stress: The Ultimate Science-Backed Guide Admin

Quick Links

  • Stock Market Live
  • Parliament Election 2082
Copyright 2026 — Youths Forum. All rights reserved. Blogsy WordPress Theme