ReactJS-The Beginner Master Class
  • React In the Beginning
    • Lesson 1 - Demo: Build a Simple React App - Fast
    • Lesson 2 - HTML Review
    • Lesson 3 - CSS Review
    • Lesson 4 - Modern JavaScript (JSX) Patterns
    • Lesson 5 - Set up Dev Environment
    • Hands-on Practice
  • React Fundamentals
    • Lesson 1 - Understanding Old vs New Way of Building Web Apps - SPAs
    • Lesson 2 - Motivation for Using React as the Solution to Vanilla JS
    • Lesson 3 - What is ReactJS - How it Works
    • React Code Along from Scratch
    • Lesson 4 - Create and Run a React Project with Vite - Full Overview
    • Lesson 5 - Create Hook by State Management in React
    • Lesson 6 - React Project File and Folder Walkthrough
    • Lesson 7 - JSX and How React Treats the DOM & JSX Compilation(by Babeljs) - Overview
    • Lesson 8 - Understanding the Main Files - App.jsx and main.jsx
    • Lesson 9 - Props and One-Way Data Flow - Overview
    • Lesson 10 - Google Bookshelf App - Ver 1.0
    • Hands-on Practice I
    • Hands-on Practice II
  • React State and Styling
    • Lesson 1 - Pulling Book Data from a Different Data File
    • Lesson 2 - Overview of How State Works in React
    • Lesson 3 - RandomQuote App
    • Lesson 4 - Lifting State Up - React Pattern Overview
    • Hands-On - Simple Counter
  • Forms and Interactivity - Grocery List App
    • Lesson 1 - Setup a Simple Form and Input
    • Lesson 2 - Build Form Profile App Using Multi-input Form Data
    • Hands-on : Build a Grocery List App
  • Connecting to the Backend - Consuming APIs - UseEffect Hook
    • Lesson 1 - Connecting to the Back End - Understanding Side Effects, Hooks and useEffect - Overview
    • Lesson 2 - Fetching Data from the Backend the Right Way with useEffect Hook
    • Lesson 3 - Setting Up Loading State
    • Hands-on :Use Dependency Array and Adding Values that Control Side Effects
  • Solo Project 1
  • RESTful APIs :Build a BookSearch App -Ver 2.0
    • Lesson 1: Build and test RESTful APIs with Postman
    • Lesson 2 - BookShelf App Structure
    • Lesson 3 - Create NavBar.jsx Component
    • Lesson 4 - Create Footer Component
    • Lesson 5 - Create BookList.jsx Component
    • Lesson 6 - Create BookCard.jsx Component
    • Lesson 7 - Creating Custom Hooks - useBooks and api-client
    • Lesson 8 - Controlling Network Activities in React with AbortController
    • Lesson 9 - Show Book Details in a Modal - Working
    • Lesson 10 - Bookshelf App Summary
  • Multi-Page Applications (MPAs)
    • Build a Multi-Page React Application
    • Multi-Page React Application
    • Hands-on Practice
  • Backend Frameworks-NEXT.JS
    • Migrating from React to Next.js
    • Lesson 1: Key Concepts of NodeJS and Express for Backend Web Development
    • Lesson 2: How to set up a new Next.js project
    • Lesson 3: How to create Layouts and Pages
    • Hands-on Practice 1
    • Hands on Practice 2
      • New Project & Folder Structure
      • File-Based Routing
      • Server vs Client Components & Router Hooks
      • Start On The Navbar
      • Navbar Links, Dropdowns & React Icons
      • Active Links & Conditional Rendering
      • Homepage Components
      • Properties Page
      • Property Card Dynamic Data
      • Home Property Listings
      • Custom Not Found & Loading Pages
  • Git and GitHubs
    • Git Installation
    • Git Commands
    • GitHub Repository
    • Hands-on Practice
  • Database in Application
    • React Supabase CRUD
    • Hands-on: Note Taking App
  • NoSQL Database
    • Installing MongoDB Community Edition
    • System Env Path Setting
    • How to use MongoDB Shell
    • How to Connect and Use Mongosh in VS Code via MongoDB Extension
    • MongoDB Guide
  • Solo Project 2
  • Deployment and Web Hosting
    • Lesson 1. React+Vite+TS+Shadcn Project
    • Lesson 2. Deploying a React Vite App to Vercel from Vercel CLI
    • Lesson 3 Connecting to GitHub Repo and Automate Deployment
  • Solo Project 3
  • Final Term Project
    • Level 1 Team Project
    • Level 1 Team Project
    • Level 1 Team Project
    • Level 1 Team Project
    • Level 2 Team Project
    • Level 2 Team Project
    • Level 3 Team Project
    • Level 3 Team Project
Powered by GitBook
On this page
  • Understanding React Building Blocks
  • What is React Component?
  • Illustrative Example for State Management
  1. React Fundamentals

Lesson 5 - Create Hook by State Management in React

PreviousLesson 4 - Create and Run a React Project with Vite - Full OverviewNextLesson 6 - React Project File and Folder Walkthrough

Last updated 2 months ago

Understanding React Building Blocks

What is React Component?

Technically, a React component is a reusable piece of UI code. It's like a blueprint for a specific section of your application's interface. Components can be as simple as a button or as complex as a complete user profile section.

Key Characteristics:

  • Self-Contained: Each component manages its own state and logic, making them independent and easier to maintain.

  • Reusability: Once created, you can reuse the same component multiple times within your application, reducing code duplication.

  • Composability: Components can be nested within each other to build complex UIs. This allows you to create a hierarchical structure for your application's components.

  • JSX: Components are often defined using JSX, a syntax extension to JavaScript that allows you to write HTML-like code within your JavaScript files.

JSX and How React Treats the DOM - Overview

Illustrative Example for State Management

  1. Introduction to State in React and the State Management with useState

  • create AppHook.jsx component in src folder

  • create BookNoHooK.jsx and BookWithHook.jsx in sr/components folder

  • Use bootstrap package for styling along with App.css

  • update main entry file main.jsx with <AppHook /> by importing such as

    import AppHook from './AppHook.jsx'
// AppHook.jsx Layout
AppHook (Component)
├── <> (React Fragment)
│   ├── h2 (text="Your favorable Book List")
│   └── div (className="card-container card-body")
│       ├── map (booksData.items.map(...))
│       │   ├── BookNoHook (Component)
│       │   │   ├── ... (props: key, title, author, description, subtitle, image)
│       ├── map (booksData.items.map(...))
│       │   ├── BookWithHook (Component)
│       │   │   ├── ... (props: key, title, author, description, subtitle, image)
// AppHook.jsx
import React from 'react'
import 'bootstrap/dist/css/bootstrap.min.css'
import booksData from './components/data.js'
import BookNoHook from './components/BookNoHook.jsx'
import BookWithHook from './components/BookWithHook.jsx'
import './App.css'

function AppHook() {
  return (
    <>
      <h2> Your favorable Book List </h2>
      <div className="card-container card-body">
        {booksData.items.map((book, index) => (
          <BookNoHook
            key={index}
            title={book.volume.title}
            author={book.volume.authors}
            description={book.volume.description}
            subtitle={book.volume.subtitle}
            image={book.volume.image}
          />
        ))}
        {/* <BookWithHook /> */}
      </div>
    </>
  )
}

export default AppHook
// App.css
/** @format */

#root {
  max-width: 1280px;
  margin: 0 auto;
  padding: 2rem;
  text-align: center;
}

/*
 Added for the UserProfile Card component
*/
.profile-container {
  display: flex;

}

div>img {
  padding-right: 10px;
  margin-top: 10px;
  max-width: 350px;
  height: 180px;
  border-radius: 20px;
}

div>p {
  text-align: left;
  margin-left: 10px;
}

.user-profile {
  border: 1px solid #cc7979;
  border-radius: 15px;
  padding: 20px;
  max-width: 600px;
  margin: 20px auto;
  text-align: center;
}

.logo {
  height: 6em;
  padding: 1.5em;
  will-change: filter;
  transition: filter 300ms;
}

.logo:hover {
  filter: drop-shadow(0 0 2em #646cffaa);
}

.logo.react:hover {
  filter: drop-shadow(0 0 2em #61dafbaa);
}

@keyframes logo-spin {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}

@media (prefers-reduced-motion: no-preference) {
  a:nth-of-type(2) .logo {
    animation: logo-spin infinite 20s linear;
  }
}

.card {
  padding: 2em;
}

.read-the-docs {
  color: #888;
}

.calculator-result {
  margin-top: 20px;
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.calculator {
  max-width: 400px;
  margin: 20px auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 8px;
}

.calculator input[type="number"] {
  width: 100%;
  padding: 8px;
  margin: 10px 0;
  border: 1px solid #ccc;
  border-radius: 4px;
}
.operators {
  display: flex;
  justify-content: space-around;
  margin: 20px 0;
}
.operators label {
  display: flex;
  align-items: center;
  gap: 4px;
}

button {
  width: 100%;
  padding: 10px;
  background-color: #08417b;
  color: rgb(252, 107, 16);
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:hover {
  background-color: #597ca1;
}

.navbar-a {
  margin: 10px;
}
.card-container {
  display: flex;
  justify-content: center;
  /* Centers horizontally */
  align-items: center;
  /* Centers vertically */
  flex-direction: column;
  /* Optional: if you want the cards to stack vertically */
 /*  height: 100vh; */
  /* Optional: full viewport height */
  
}
//BookNoHoo.jsx
/** @format */

function BookNoHook({ title, author, description, subtitle, image }) {

  var isRead = true

  return (
    <div className="profile-container user-profile">
      <div>
        <img src={image} alt={title} />
      </div>
      <div>
        <h2>Title: {title}</h2>
        <h4>Subtitle: {subtitle}</h4>
        <h3>By {author}</h3>
        <p>Description: {description}</p>
        <button
          className="btn btn-primary"
          name="No Hook"
          value={isRead ? 'Read' : 'Unread'}
          onClick={(e) => {
            isRead = !isRead
            console.log('Status', isRead)
              console.log(e.target.name, e.target.value)
          }}>
          {isRead ? 'Read' : 'Unread'} //Not working. Why???
        </button>
      </div>
    </div>
  )
}
export default BookNoHook
// BookWithHook.jsx
/** @format */

import { useState } from "react";

function BookWithHook({ title, author, description, subtitle, image }) {
  const [isRead, setIsRead] = useState(false);// state

  function onIsRead(event) {  //event handler for button click
    setIsRead(!isRead)
    console.log(event.target)
  }
  return (
    <div className="profile-container user-profile">
      <div>
        <img src={image} alt={title} />
      </div>
      <div>
        <h2>Title: {title}</h2>
        <h4>Subtitle: {subtitle}</h4>
        <h3>By {author}</h3>
        <p>Description: {description}</p>
        <button className="btn btn-primary" 
         name="With Hook" 
         value= {isRead ? 'Read' : 'Unread'}
         onClick={onIsRead}>
          {isRead ? "Read" : "Unread"}
        </button>
      </div>
    </div>
  );
}
export default BookWithHook;
// Some code
/** @format */

const booksData = {
  items: [
    {
      volume: {
        title: "Effective Java",
        subtitle: "Programming Language Guide",
        authors: ["Joshua Bloch"],
        description:
          "From the source of Java's design, this guide provides the best practices and expert insights for professional Java developers. Ideal for enhancing coding efficiency and understanding Java's capabilities.",
        image:
          "http://books.google.com/books/content?id=ka2VUBqHiWkC&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api",
      },
    },
    {
      volume: {
        title: "Clean Code",
        subtitle: "A Handbook of Agile Software Craftsmanship",
        authors: ["Robert C. Martin"],
        description:
          "A must-read for developers striving to write clean code that enhances readability and maintainability. Includes practical advice and real-world examples from software engineering.",
        image:
          "http://books.google.com/books/content?id=_i6bDeoCQzsC&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api",
      },
    },
    {
      volume: {
        title: "Head First Java",
        subtitle: "A Brain-Friendly Guide",
        authors: ["Kathy Sierra", "Bert Bates"],
        description:
          "An engaging, visually-rich approach to learning Java, suitable for beginners who want a complete understanding of object-oriented programming and Java basics.",
        image:
          "http://books.google.com/books/content?id=lXEBwv0LYogC&printsec=frontcover&img=1&zoom=5&source=gbs_api",
      },
    },
    {
      volume: {
        title: "Eloquent JavaScript, 3rd Edition",
        subtitle: "A Modern Introduction to Programming",
        authors: ["Marijn Haverbeke"],
        description:
          "Completely revised and updated, this best-selling introduction to programming in JavaScript focuses on writing real applications.",
        image:
          "http://books.google.com/books/content?id=FSVTDwAAQBAJ&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api",
      },
    },
    {
      volume: {
        title: "Professional Java for Web Applications",
        subtitle: "Comprehensive Guide to Spring Framework",
        authors: ["Nicholas S. Williams"],
        description:
          "The comprehensive Wrox guide for creating Java web applications for the enterprise This guide shows Java software developers and software engineers how to build complex web applications in an enterprise environment.",
        image:
          "http://books.google.com/books/content?id=cHr0AgAAQBAJ&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api",
      },
    },
  ],
};
export default booksData;
  1. Check out the console output at Chrome Dev Tools (CTRL+SHIFT+I) to see Status change when clicked in two cases: BookNoHook and BookWithHook

With NO Hook
With useState Hook