Advanced Web Designing — Study Notes

Unit 02

React fundamentals — organized as exam-ready answers.

4 Questions 1 × 2 Marks + 3 × 5 Marks Advanced Web Designing
01
2 Marks Question

What are Props in React?

Props (Properties) are used in React to pass data from a parent component to a child component. They allow components to be reusable by receiving different values from their parent.

Props are read-only, meaning the child component should not directly modify the props it receives.

Example
function Student(props) {
    return <h2>Student Name: {props.name}</h2>;
}

function App() {
    return <Student name="Rahul" />;
}

Here, name="Rahul" is a prop passed from the App (parent) component to the Student (child) component. The child accesses it using props.name.

In shortProps provide a way for parent → child communication and help make React components reusable.
02
5 Marks Question

What are Components in React? Explain in Detail.

Components are the building blocks of a React application. A component is a reusable piece of UI that defines how a particular part of a web page should appear and behave.

Components divide a large application into small, independent, and reusable parts, making the application easier to develop and maintain.

Types of Components

React mainly has two types of components:

01
Functional Components

A Functional Component is a JavaScript function that returns JSX. It is the commonly used approach for creating components in modern React.

Example
function Welcome() {
    return <h1>Welcome to React</h1>;
}

export default Welcome;

Here, Welcome is a functional component that returns an <h1> element. Functional components can use Hooks such as useState() and useEffect() to manage state and perform other React operations.

02
Class Components

A Class Component is a JavaScript class that extends React.Component and contains a render() method that returns JSX.

Example
import React from "react";

class Welcome extends React.Component {
    render() {
        return <h1>Welcome to React</h1>;
    }
}

export default Welcome;

Here, Welcome is a class component and the render() method returns the UI.

Advantages of Components

Reusability
The same component can be used multiple times.
Modularity
A large application can be divided into smaller components.
Maintainability
Changes can be made to individual components without affecting the entire application.
Independent UI
Each component can manage its own UI and behaviour.
Data Handling
Components can receive data through props and manage data using state.
ConclusionComponents allow React applications to be divided into small, reusable, and independent UI parts. React supports both Functional Components and Class Components, with functional components being commonly used in modern React.
03
5 Marks Question

Explain Form Handling in React

A form in React is used to collect input from users, such as name, email, message, etc. Forms are created using JSX elements such as <form>, <input>, <button>, <textarea>, and <select>.

React handles form data differently from plain HTML by generally using Controlled Components.

Controlled Components

A controlled component is a form element whose value is controlled by React state. The input's value comes from state, and whenever the user changes the input, the state is updated using onChange.

Example
import { useState } from "react";

function SimpleForm() {
    const [name, setName] = useState("");

    return (
        <form>
            <input
                type="text"
                value={name}
                onChange={(e) => setName(e.target.value)}
            />

            <p>You typed: {name}</p>
        </form>
    );
}

Here, value={name} makes the input display the current state value, onChange runs whenever the user types something, and setName() updates the state. React therefore always knows the current value of the input.

Form Submission

The onSubmit event is used to handle form submission.

Example
function SimpleForm() {
    const [name, setName] = useState("");

    const handleSubmit = (e) => {
        e.preventDefault();
        console.log("Submitted:", name);
    };

    return (
        <form onSubmit={handleSubmit}>
            <input
                value={name}
                onChange={(e) => setName(e.target.value)}
            />

            <button type="submit">Submit</button>
        </form>
    );
}

The important statement is e.preventDefault();. Normally, submitting an HTML form reloads the page. e.preventDefault() prevents the default page reload, allowing React to handle the submission using JavaScript.

Handling Multiple Fields

Multiple form fields can be stored in a single state object:

const [formData, setFormData] = useState({
    name: "",
    email: ""
});

const handleChange = (e) => {
    setFormData({
        ...formData,
        [e.target.name]: e.target.value
    });
};

Here, e.target.name identifies which input was changed, e.target.value contains the entered value, and ...formData preserves the existing field values.

Other Form Components

React also supports controlled textarea and select elements using the same value and onChange approach.

ConclusionReact form handling uses state, controlled components, onChange, and onSubmit to keep form data under React's control and process user input without unnecessarily reloading the page.
04
5 Marks Question

Explain Hooks in React with Examples. Describe the Rules to Follow When Using a Hook.

Hooks are special functions in React that allow functional components to use React features such as state, lifecycle-related behavior, context, DOM access, and performance optimization. All React Hooks start with the word use. They were introduced in React 16.8, allowing functional components to use features that previously required class components.

Common React Hooks

useState()
Stores and updates data/state in a functional component.
useEffect()
Performs side effects such as API calls, timers and event listeners.
useContext()
Shares data between components without passing props through every intermediate component.
useRef()
Accesses DOM elements or stores a value without causing a re-render.
useReducer()
Manages complex state.
useCallback()
Remembers a function to help with performance.
useMemo()
Remembers the result of an expensive calculation.

Example of useState()

useState() is used to store and update data inside a functional component. When the state changes, React re-renders the component and updates the UI.

Example
import { useState } from "react";

function App() {
    const [count, setCount] = useState(0);

    return (
        <>
            <h1>{count}</h1>
            <button onClick={() => setCount(count + 1)}>
                Increase
            </button>
        </>
    );
}

Here, count stores the current value and setCount() updates it.

Example of useEffect()

useEffect() is used to perform side effects after a component is rendered, such as API calls, fetching data, timers, event listeners, or updating the browser title.

Example
import { useEffect } from "react";

function App() {
    useEffect(() => {
        alert("Welcome Students");
    }, []);

    return <h1>Hello</h1>;
}

Rules to Follow When Using Hooks

01
Call Hooks only at the top level

Hooks should not be called inside loops, conditions, nested functions, or if statements. They should be called at the top level of the functional component.

02
Call Hooks only from React functions

Hooks should be called from a React functional component or from a custom Hook, not from an ordinary JavaScript function.

03
Do not call Hooks conditionally

For example, avoid:

if (isLoggedIn) {
    useState(0); // ❌
}

Instead, call the Hook first and put the condition around the logic that uses its value.

04
Use the correct Hook naming convention

React Hooks start with use, such as useState, useEffect, and useContext. Custom Hooks should also start with use, for example useStudentData.

ConclusionHooks make functional components more powerful by providing access to state, effects, context, DOM access and other React features without requiring class components. They also encourage less code, reusable logic and easier-to-understand components.