React.js-Routing, useState & useEffect

7. Routing – Simple Navigation

Routing allows navigation between different pages/views in a single-page application.

Setup React Router

First install React Router:

npm install react-router-dom

Navigation Component

Navigation.js

import React from 'react';                          // Line 1: Import React
import { Link } from 'react-router-dom';            // Line 2: Import Link for navigation

function Navigation() {                             // Line 3: Navigation component
  return (                                          // Line 4: Return JSX
    <nav className="navbar">                        // Line 5: Navigation container
      <div className="nav-brand">                   // Line 6: Brand/logo section
        <h2>My Website</h2>                         // Line 7: Website title
      </div>                                        // Line 8: Close brand section
      <ul className="nav-links">                    // Line 9: Navigation links list
        <li><Link to="/">Home</Link></li>           // Line 10: Home link
        <li><Link to="/about">About</Link></li>     // Line 11: About link
        <li><Link to="/contact">Contact</Link></li> // Line 12: Contact link
        <li><Link to="/courses">Courses</Link></li> // Line 13: Courses link
      </ul>                                         // Line 14: Close links list
    </nav>                                          // Line 15: Close navigation
  );                                                // Line 16: Close return
}                                                   // Line 17: Close function

export default Navigation;                          // Line 18: Export component

Page Components

Home.js

import React from 'react';                          // Line 1: Import React

function Home() {                                   // Line 2: Home page component
  return (                                          // Line 3: Return JSX
    <div className="page">                          // Line 4: Page container
      <h1>Welcome to Home Page</h1>                 // Line 5: Page title
      <p>This is the homepage of our website.</p>   // Line 6: Page content
      <div className="home-features">               // Line 7: Features section
        <h3>What we offer:</h3>                     // Line 8: Features title
        <ul>                                        // Line 9: Features list
          <li>Quality education</li>                // Line 10: Feature item
          <li>Expert instructors</li>               // Line 11: Feature item
          <li>Interactive learning</li>             // Line 12: Feature item
        </ul>                                       // Line 13: Close list
      </div>                                        // Line 14: Close features
    </div>                                          // Line 15: Close page
  );                                                // Line 16: Close return
}                                                   // Line 17: Close function

export default Home;                                // Line 18: Export component

About.js

import React from 'react';                          // Line 1: Import React

function About() {                                  // Line 2: About page component
  return (                                          // Line 3: Return JSX
    <div className="page">                          // Line 4: Page container
      <h1>About Us</h1>                             // Line 5: Page title
      <p>We are passionate about teaching React!</p> // Line 6: About description
      <div className="team-info">                   // Line 7: Team section
        <h3>Our Mission</h3>                        // Line 8: Mission title
        <p>To make learning React simple and fun.</p> // Line 9: Mission statement
      </div>                                        // Line 10: Close team section
    </div>                                          // Line 11: Close page
  );                                                // Line 12: Close return
}                                                   // Line 13: Close function

export default About;                               // Line 14: Export component

Main App with Router

App.js

import React from 'react';                                    // Line 1: Import React
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom'; // Line 2: Import routing components
import Navigation from './Navigation';                        // Line 3: Import Navigation
import Home from './Home';                                    // Line 4: Import Home page
import About from './About';                                  // Line 5: Import About page
import Contact from './Contact';                              // Line 6: Import Contact page
import Courses from './Courses';                              // Line 7: Import Courses page

function App() {                                              // Line 8: Main App component
  return (                                                    // Line 9: Return JSX
    <Router>                                                  // Line 10: Router wrapper
      <div className="app">                                   // Line 11: App container
        <Navigation />                                        // Line 12: Navigation component
        <div className="page-content">                        // Line 13: Content area
          <Routes>                                            // Line 14: Routes container
            <Route path="/" element={<Home />} />             // Line 15: Home route
            <Route path="/about" element={<About />} />       // Line 16: About route
            <Route path="/contact" element={<Contact />} />   // Line 17: Contact route
            <Route path="/courses" element={<Courses />} />   // Line 18: Courses route
          </Routes>                                           // Line 19: Close Routes
        </div>                                                // Line 20: Close content area
      </div>                                                  // Line 21: Close app container
    </Router>                                                 // Line 22: Close Router
  );                                                          // Line 23: Close return
}                                                             // Line 24: Close function

export default App;                                           // Line 25: Export App

Small Task: Create a “Services” page component that displays 3 services in a list. Add it to the navigation and routing. (Max 10 lines)


8. useState – Toggle Visibility

useState manages component state that can change over time and triggers re-renders.

ToggleVisibility Component

ToggleVisibility.js

import React, { useState } from 'react';            // Line 1: Import React and useState hook

function ToggleVisibility() {                       // Line 2: Component function
  const [isVisible, setIsVisible] = useState(false); // Line 3: State for visibility (initially hidden)
  const [buttonText, setButtonText] = useState('Show Text'); // Line 4: State for button text
  
  const toggleText = () => {                        // Line 5: Toggle function
    setIsVisible(!isVisible);                       // Line 6: Flip visibility state
    setButtonText(isVisible ? 'Show Text' : 'Hide Text'); // Line 7: Update button text based on state
  };                                                // Line 8: Close toggle function
  
  return (                                          // Line 9: Return JSX
    <div className="toggle-app">                    // Line 10: Main container
      <h2>Toggle Visibility Demo</h2>               // Line 11: App title
      
      <button                                       // Line 12: Toggle button
        onClick={toggleText}                        // Line 13: Click handler
        className="toggle-btn"                      // Line 14: CSS class
        style={{                                    // Line 15: Button styles
          backgroundColor: isVisible ? '#e74c3c' : '#3498db', // Line 16: Dynamic color
          color: 'white',                           // Line 17: Text color
          padding: '10px 20px',                     // Line 18: Padding
          border: 'none',                           // Line 19: No border
          borderRadius: '5px',                      // Line 20: Rounded corners
          cursor: 'pointer'                         // Line 21: Pointer cursor
        }}                                          // Line 22: Close styles
      >                                             // Line 23: Close button opening tag
        {buttonText}                                // Line 24: Dynamic button text
      </button>                                     // Line 25: Close button
      
      {isVisible && (                               // Line 26: Conditional rendering
        <div className="hidden-content">           // Line 27: Content container
          <h3>🎉 Surprise! I'm visible now!</h3>   // Line 28: Hidden content title
          <p>This text was hidden and now it's showing!</p> // Line 29: Hidden content
          <p>You can toggle me on and off.</p>     // Line 30: More content
        </div>                                      // Line 31: Close content container
      )}                                            // Line 32: Close conditional rendering
      
      <div className="state-info">                  // Line 33: State info section
        <p>Current state: <strong>{isVisible ? 'Visible' : 'Hidden'}</strong></p> // Line 34: Show current state
      </div>                                        // Line 35: Close state info
    </div>                                          // Line 36: Close main container
  );                                                // Line 37: Close return
}                                                   // Line 38: Close function

export default ToggleVisibility;                   // Line 39: Export component

Key useState Concepts:

  • useState returns array: [value, setter]
  • State updates trigger re-renders
  • Conditional rendering with && operator
  • State updates are asynchronous

Small Task: Add a click counter that shows how many times the toggle button was clicked. (Max 10 lines)


9. useEffect – Digital Clock

useEffect handles side effects like timers, API calls, and subscriptions.

DigitalClock Component

DigitalClock.js

import React, { useState, useEffect } from 'react'; // Line 1: Import React hooks

function DigitalClock() {                           // Line 2: Clock component function
  const [time, setTime] = useState(new Date());     // Line 3: State for current time
  const [isRunning, setIsRunning] = useState(true); // Line 4: State for clock running status
  
  useEffect(() => {                                 // Line 5: useEffect hook for side effects
    let interval;                                   // Line 6: Declare interval variable
    
    if (isRunning) {                                // Line 7: Check if clock should run
      interval = setInterval(() => {                // Line 8: Create timer interval
        setTime(new Date());                        // Line 9: Update time every second
      }, 1000);                                     // Line 10: Update every 1000ms (1 second)
    }                                               // Line 11: Close if condition
    
    return () => {                                  // Line 12: Cleanup function
      if (interval) {                               // Line 13: Check if interval exists
        clearInterval(interval);                    // Line 14: Clear the interval
      }                                             // Line 15: Close if condition
    };                                              // Line 16: Close cleanup function
  }, [isRunning]);                                  // Line 17: Dependency array - effect runs when isRunning changes
  
  const toggleClock = () => {                       // Line 18: Function to start/stop clock
    setIsRunning(!isRunning);                       // Line 19: Toggle running state
  };                                                // Line 20: Close toggle function
  
  const formatTime = (date) => {                    // Line 21: Time formatting function
    return date.toLocaleTimeString('en-US', {       // Line 22: Format time with options
      hour12: true,                                 // Line 23: Use 12-hour format
      hour: '2-digit',                              // Line 24: Two-digit hour
      minute: '2-digit',                            // Line 25: Two-digit minute
      second: '2-digit'                             // Line 26: Two-digit second
    });                                             // Line 27: Close toLocaleTimeString
  };                                                // Line 28: Close formatTime function
  
  const formatDate = (date) => {                    // Line 29: Date formatting function
    return date.toLocaleDateString('en-US', {       // Line 30: Format date with options
      weekday: 'long',                              // Line 31: Full weekday name
      year: 'numeric',                              // Line 32: Full year
      month: 'long',                                // Line 33: Full month name
      day: 'numeric'                                // Line 34: Day number
    });                                             // Line 35: Close toLocaleDateString
  };                                                // Line 36: Close formatDate function

  return (                                          // Line 37: Return JSX
    <div className="digital-clock">                 // Line 38: Main clock container
      <h2>Digital Clock</h2>                        // Line 39: Clock title
      
      <div className="clock-display">               // Line 40: Clock display area
        <div className="time">                      // Line 41: Time container
          <h1>{formatTime(time)}</h1>               // Line 42: Display formatted time
        </div>                                      // Line 43: Close time container
        
        <div className="date">                      // Line 44: Date container
          <p>{formatDate(time)}</p>                 // Line 45: Display formatted date
        </div>                                      // Line 46: Close date container
      </div>                                        // Line 47: Close clock display
      
      <div className="clock-controls">              // Line 48: Controls container
        <button                                     // Line 49: Start/stop button
          onClick={toggleClock}                     // Line 50: Toggle click handler
          className={isRunning ? 'stop-btn' : 'start-btn'} // Line 51: Dynamic CSS class
        >                                           // Line 52: Close button opening tag
          {isRunning ? 'Stop Clock' : 'Start Clock'} // Line 53: Dynamic button text
        </button>                                   // Line 54: Close button
        
        <p className="status">                      // Line 55: Status paragraph
          Status: <span className={isRunning ? 'running' : 'stopped'}> // Line 56: Status with dynamic class
            {isRunning ? 'Running' : 'Stopped'}    // Line 57: Status text
          </span>                                   // Line 58: Close status span
        </p>                                        // Line 59: Close status paragraph
      </div>                                        // Line 60: Close controls container
    </div>                                          // Line 61: Close main container
  );                                                // Line 62: Close return
}                                                   // Line 63: Close function

export default DigitalClock;                       // Line 64: Export component

Key useEffect Concepts:

  • useEffect(() => {}, []) – Runs after every render
  • Dependency array [] controls when effect runs
  • Return function from useEffect for cleanup
  • setInterval creates recurring timer
  • clearInterval stops the timer

useEffect Patterns:

// Run once on mount
useEffect(() => {}, []);

// Run on every render
useEffect(() => {});

// Run when specific value changes
useEffect(() => {}, [value]);

// Cleanup on unmount
useEffect(() => {
  return () => { /* cleanup */ };
}, []);

Small Task: Add a timezone selector dropdown that changes the clock’s timezone display. Use toLocaleTimeString with different timezone options. (Max 10 lines)

Complete Demo App

App.js

import React from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import Navigation from './Navigation';
import ToggleVisibility from './ToggleVisibility';
import DigitalClock from './DigitalClock';

function App() {
  return (
    <Router>
      <div className="app">
        <Navigation />
        <div className="page-content">
          <Routes>
            <Route path="/" element={<div><h1>Home</h1></div>} />
            <Route path="/toggle" element={<ToggleVisibility />} />
            <Route path="/clock" element={<DigitalClock />} />
          </Routes>
        </div>
      </div>
    </Router>
  );
}

export default App;

These examples demonstrate fundamental React concepts: Routing for navigation, useState for component state management, and useEffect for handling side effects and lifecycle events.

Leave a Reply

Your email address will not be published. Required fields are marked *