0% found this document useful (0 votes)
4 views29 pages

React Notes

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views29 pages

React Notes

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Introduction

Fundamentals of React:
Introduction

1. What Is React?

●​ Definition: React is a JavaScript library for building user interfaces by breaking the
UI into reusable pieces called components.
●​ Key Idea: Instead of writing one large block of code for your entire page, you create
tiny, self-contained components (like buttons, forms, or menus) and assemble them
to build complex UIs.

🔍 Analogy: Think of a web page as a car showroom. Each component (button, form,
menu) is like a car model you can place, configure, and reuse elsewhere in the showroom.

2. SPA vs MPA
Feature SPA (Single-Page App) MPA (Multi-Page App)

Page Loading One HTML file; JavaScript dynamically Each route loads a new HTML
swaps views page

Navigation Client-side routing (no full page reload) Server-side routing (full reload)

User Faster, more app-like feel Traditional, sometimes slower


Experience feel

Use Cases Dashboards, social media, complex Blogs, marketing sites,


UIs content-driven sites

Example: Gmail and Facebook are SPAs—they feel like desktop apps.
Traditional blogs like WordPress sites are MPAs.

3. Why Use React?

1.​ Virtual DOM


○​ React maintains a lightweight copy of the UI (the Virtual DOM) in memory.
○​ On state or prop changes, React diffs the new Virtual DOM against the
previous one, then patches only the changed parts in the real DOM.
○​ Benefit: Minimizes expensive DOM operations, boosting performance and
making updates snappy.
2.​ Component-Driven Architecture
○​ Build your UI in small, self-contained components.
○​ Each component manages its own logic and rendering, making code easier to
read, maintain, and test.
○​ Benefit: Encourages code reuse—like Lego blocks you can assemble in
different ways.

Analogy: If a website is a house, React components are like rooms built from
standard-sized bricks—each room is self-contained but fits perfectly with the
others.

4. Interview Question

Q: What is the Virtual DOM and why is it useful?​


A: The Virtual DOM is an in-memory representation of the real DOM. React
uses it to batch and minimize updates by diffing changes and only applying
necessary patches to the real DOM. This process reduces direct DOM
manipulations, resulting in faster and more efficient UI updates, which improves
overall app performance and responsiveness.
Project Setup
Fundamentals of React: Project Setup

1. Vite vs Create React App

●​ Vite
○​ Uses native ES modules in the browser.
○​ Lightning‑fast hot module replacement (HMR): only changed modules reload.
○​ Minimal bundling during development—almost instant startup.

Analogy: Vite is like driving a sports car—instant acceleration—while CRA is


like a heavy truck that takes time to get going.

2. File & Folder Structure

Organizing your code helps teams collaborate and maintain large apps:

src/
components/ # Reusable UI pieces (Buttons, Cards, Modals)
pages/ # Top-level views or routes (Home, Dashboard)
assets/ # Images, fonts, icons, static files
services/ # API calls, context providers, utility functions
App.jsx # Root component that ties everything together
index.jsx # Entry point: renders <App /> into the DOM

Tip: Co-locate tests (e.g., Button.test.jsx) next to components to simplify


maintenance.

3. Installing React & Dependencies


Initialize a new project with Vite:​
npm init vite@latest my-app --template react
cd my-app

1.​ npm install

Add common libraries:​


# Routing
npm install react-router-dom
# Styling
npm install tailwindcss postcss autoprefixer
2.​ npx tailwindcss init

Pro Tip: Use pnpm or yarn for faster installs and built‑in workspaces.

4. How React Renders to the DOM


import React from 'react';
import { createRoot } from 'react-dom/client';
import App from './App';

const container = document.getElementById('root');


const root = createRoot(container);
root.render(<App />);

●​ createRoot: Enables React’s concurrent rendering features.


●​ root.render(<App />): Mounts your React component tree under the <div
id="root"> in your index.html.

Behind the Scenes: React builds a Virtual DOM tree in memory first, then
syncs it with the real DOM to optimize performance.

5. Interview Question

Q: Why might you choose Vite over Create React App?​


A: Vite leverages native ES modules for ultra‑fast reloads and starts the dev
server almost instantly. By contrast, CRA bundles everything upfront, resulting in
slower startup and HMR, which can slow down development feedback loops.
JSX Syntax
Fundamentals of React: JSX Syntax

1. Embedding JavaScript in JSX

●​ What it is: You can include any JavaScript expression inside curly braces ({}) within
JSX.
●​ Why it’s useful: Lets you compute values, loop over arrays, or call functions directly
in your markup.

function Greeting({ name }) {


const message = `Hello, ${name}!`;
return (
<div>
<h1>{message}</h1>
<p>{new Date().toLocaleTimeString()}</p>
<ul>
{[1, 2, 3].map(i => <li key={i}>Item {i}</li>)}
</ul>
</div>
);
}

Analogy: Think of JSX as a recipe where {} let you drop in fresh ingredients
(JS values) right into the final dish.

2. Differences from HTML


HTML JSX

class="btn className="btn primary"


primary"

for="email" htmlFor="email"

Lowercase tags Custom components must be capitalized

Inline style string Object syntax: { style={{ color: 'red' }}}

Attributes quoted Curly braces for JS values

●​ ​
JSX isn’t a string or HTML—it compiles to React.createElement calls under the
hood.
3. JSX Expressions vs Statements

●​ Expressions: Anything that produces a value. You can use expressions inside {}.
○​ Examples: literals (42), ternary (x > 0 ? 'Yes' : 'No'), function calls
(formatDate(date)).
○​ Allowed in JSX:​
<p>{user.isLoggedIn ? 'Welcome back!' : 'Please log in'}</p>
●​ Statements: Perform actions but don’t return values (e.g., if, for, while, const).
○​ Not allowed directly in JSX. Move logic above the return or inside helper
functions.

//❌ Invalid:
return <div>{if (open) <Modal />}</div>;

//✅ Correct:
if (!open) return null;
return <Modal />;

4. JSX Attributes (className, htmlFor, etc.)

●​ className instead of class: Avoids clashing with JS reserved word.​


<button className="btn primary">Click me</button>

htmlFor instead of for on <label>: Links label to form input.​


<label htmlFor="email">Email</label>

●​ <input id="email" type="email" />


●​ Other attribute differences:
○​ tabIndex (camelCase)
○​ defaultValue vs value for form defaults
○​ onClick, onChange: event handlers must be camelCase and passed as
functions.

Tip: If you need a non-standard attribute, prefix it with data-, e.g., <div
data-user-id={user.id} /> for custom data attributes.
Components
Fundamentals of React: Components

1. Functional Components

●​ Definition: JavaScript functions that return JSX. They receive props as an


argument.

Example:​
function Button({ label, onClick }) {
return <button onClick={onClick}>{label}</button>;

●​ }
●​ Benefit: Simpler syntax compared to class components, with access to Hooks for
state and lifecycle.

2. Nesting Components
Composition: You can include one component inside another to build complex UIs.​
function Card({ title, children }) {
return (
<div className="card">
<h2>{title}</h2>
<div>{children}</div>
</div>
);
}

function App() {
return (
<Card title="Welcome!">
<p>This is a nested component example.</p>
</Card>
);

●​ }

3. Component Naming Conventions


PascalCase: Component names must start with a capital letter.​
// Correct:
function UserProfile() { ... }
// Incorrect:
●​ function userprofile() { ... }
●​ File Names: Match component name (e.g., UserProfile.jsx exports
UserProfile).

4. Returning Multiple Elements Using Fragments

●​ Problem: JSX must have a single parent element.

Solution: React Fragments: Use <React.Fragment> or shorthand <>…</>.​


function ListItem({ item }) {
return (
<>
<dt>{item.term}</dt>
<dd>{item.definition}</dd>
</>
);

●​ }
●​ Benefit: No extra <div> wrappers cluttering the DOM.

5. Props: Passing Data Between Components

●​ Props: Read-only inputs passed from parent to child.

Usage:​
function Greeting({ name }) {
return <p>Hello, {name}!</p>;
}

function App() {
return <Greeting name="Alice" />;

●​ }
●​ Analogy: Props are like function arguments—data you hand to a component so it
can render accordingly.

6. Default Props and Prop Destructuring


Default Props: Set fallback values if no prop is provided.​
function Button({ label, size }) {
return <button className={size}>{label}</button>;
}
Button.defaultProps = {
size: 'medium',

●​ };

Prop Destructuring: Unpack props directly in the function signature for clarity.​
function Profile({ user: { name, age }, showAge = true }) {
return (
<div>
<p>Name: {name}</p>
{showAge && <p>Age: {age}</p>}
</div>
);

●​ }

Tip: With TypeScript, use interface definitions and default parameter values
instead of defaultProps for functional components.
State Management
Fundamentals of React: State Management with
useState()

1. What Is State?

●​ Definition: State is data that changes over time within a component. Unlike props,
which are passed in from parent components, state lives inside the component and is
managed there.
●​ Analogy: Think of a component as a vending machine. State is the current selection
and credit amount inside the machine—changing as the user interacts.

2. Updating and Accessing State


Initializing State: Call the useState Hook inside a functional component:​
import { useState } from 'react';

function Counter() {
const [count, setCount] = useState(0); // count = initial state, setCount = updater

return (
<div>
<p>Current count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);

●​ }
●​ Reading State: Use the state variable (count) directly in your JSX.
●​ Updating State: Always use the setter function (setCount)—never mutate state
directly.
○​ Direct Update: setCount(count + 1)
○​ Functional Update (when new state depends on previous):​
setCount(prevCount => prevCount + 1);

3. Multiple State Variables


You can call useState multiple times to manage separate pieces of data.​
function Form() {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
return (
<form>
<input value={name} onChange={e => setName(e.target.value)} />
<input value={email} onChange={e => setEmail(e.target.value)} />
</form>
);

●​ }
●​ Benefit: Keeps state updates simple and isolated—no need to merge unrelated
fields.

4. Merging Object/Array State Updates

●​ Problem: When state is an object or array, updating it requires creating a new copy.

Object State:​
const [user, setUser] = useState({ name: '', age: 0 });

// To update age only:


setUser(prev => ({
...prev,
age: prev.age + 1

}));

Array State:​
const [items, setItems] = useState([]);

// Adding an item:
setItems(prev => [...prev, newItem]);

// Removing an item:

●​ setItems(prev => prev.filter(i => i.id !== removeId));


●​ Tip: Always use functional updater (prev => ...) when new state depends on
previous state to avoid stale closures.

5. Interview Question

Q: Why should you use a functional update (setState(prev => ...)) when
updating state based on the previous value?​
A: Functional updates ensure you’re working with the latest state value. Since
state updates are batched and asynchronous, relying on the current closure’s
state variable can lead to stale values. The functional form guarantees you
receive the most recent state in the callback.
Event Handling
Fundamentals of React: Event
Handling

1. Event Types

React normalizes browser events under a SyntheticEvent wrapper, providing cross-browser


consistency. Common handlers include:

●​ onClick: Triggered when an element is clicked.


●​ onChange: Fires when <input>, <textarea>, or <select> value changes.
●​ onSubmit: Fires when a <form> is submitted (e.g., clicking a submit button).
●​ onMouseEnter, onMouseLeave: Hover events.
●​ onKeyDown, onKeyPress, onKeyUp: Keyboard events.

<button onClick={() => alert('Clicked!')}>Click me</button>


<input onChange={e => console.log(e.target.value)} />

2. Handling Forms and Inputs


Controlled Components: Inputs whose value is tied to component state.​
function LoginForm() {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');

const handleSubmit = e => {


e.preventDefault();
console.log({ email, password });
};

return (
<form onSubmit={handleSubmit}>
<label htmlFor="email">Email:</label>
<input
id="email"
type="email"
value={email}
onChange={e => setEmail(e.target.value)}
/>

<label htmlFor="password">Password:</label>
<input
id="password"
type="password"
value={password}
onChange={e => setPassword(e.target.value)}
/>

<button type="submit">Login</button>
</form>
);

●​ }

Uncontrolled Components: Use refs to read values directly from the DOM. Less common
in React.​
function UncontrolledForm() {
const inputRef = useRef();
const handleSubmit = e => {
e.preventDefault();
console.log(inputRef.current.value);
};
return (
<form onSubmit={handleSubmit}>
<input ref={inputRef} />
<button type="submit">Submit</button>
</form>
);

●​ }

3. Preventing Default Behavior

●​ Many native events (e.g., form submissions, link clicks) cause full-page reloads or
navigation. To handle these in React, call e.preventDefault() in your event
handler.

function LinkButton() {
const handleClick = e => {
e.preventDefault();
console.log('Link click handled in React');
};
return (
<a href="/path" onClick={handleClick}>
Go somewhere
</a>
);
}
Tip: Always call e.preventDefault() at the top of your handler to avoid
unintended behavior.

4. Best Practices

●​ Pass functions, not function calls: Use onClick={handleClick}, not


onClick={handleClick()}.
●​ Avoid inline anonymous functions in large lists: They can cause unnecessary
re-renders. Instead, define handlers outside JSX or memoize with useCallback.
●​ Use semantic elements: Use <button> for clicks instead of <div> to ensure
accessibility and correct default behaviors.

5. Interview Question

Q: Why do we use e.preventDefault() in React event handlers?​


A: To stop the browser’s default action (like reloading the page on form submit
or navigating on link click), allowing React to handle the event and update the UI
without a full page refresh.
Conditional Rendering
Fundamentals of React: Conditional Rendering

1. if, Ternary, and && in JSX


if (outside JSX)​
function Greeting({ isLoggedIn }) {
if (isLoggedIn) {
return <h1>Welcome back!</h1>;
}
return <h1>Please sign in.</h1>;

●​ }
●​ Ternary Operator (? :)​
<p>{isLoggedIn ? 'Welcome back!' : 'Please sign in.'}</p>

Logical AND (&&) for simple conditionals​


{notifications.length > 0 && (
<div>You have {notifications.length} new notifications.</div>

●​ )}

Analogy: Think of these as road signs: if directs traffic to one of two routes;
the ternary picks a route inline; && only shows a sign when a condition is true.

2. Fallback UI
Show alternate UI when data is missing or loading.​
function DataList({ items }) {
if (!items || items.length === 0) {
return <p>No data found.</p>;
}
return (
<ul>
{items.map(item => <li key={item.id}>{item.name}</li>)}
</ul>
);

●​ }

Loading State with ternary:​


<div>
{isLoading ? <Spinner /> : <Content data={data} />}

●​ </div>
3. Dynamic Classes & Styles
Dynamic Class Names: Change styling based on state.​
<button className={isActive ? 'btn active' : 'btn'}>
{isActive ? 'Active' : 'Inactive'}

●​ </button>
●​ Template Literals for multiple classes:​
<div className={`card ${isSelected ? 'selected' : ''}`}>...

Dynamic Inline Styles:​


<p style={{ color: error ? 'red' : 'black' }}>
{error ? 'Error occurred' : 'All good'}

●​ </p>

Tip: Use libraries like classnames or utility-first frameworks (e.g., Tailwind) to


manage complex conditional classes cleanly.

4. Interview Question

Q: What are three ways to conditionally render UI in React and when might you
use each?​
A:

●​ if Statement: Use when you need multiple return paths or more


complex branching logic.
●​ Ternary Operator (? :): Best for simple two-option inline conditions.
●​ Logical AND (&&): Ideal for rendering something only when a condition
is true (e.g., showing a loading spinner or notification badge).

End of Module: Conditional Rendering


Forms in React
Fundamentals of React: Forms in React

1. Controlled vs Uncontrolled Components

●​ Controlled Components:
○​ Form inputs whose value is managed by React state.
○​ Every change goes through an onChange handler that updates state.
○​ Pros: Easier to validate and manipulate form data, sync UI with state.
○​ Cons: More boilerplate for large forms.

function ControlledInput() {
const [value, setValue] = useState('');
return (
<input
type="text"
value={value}
onChange={e => setValue(e.target.value)}
/>
);

●​ }
●​ Uncontrolled Components:
○​ Form inputs where you read values directly from the DOM using refs.
○​ React does not track input’s value on each keystroke.
○​ Pros: Less setup for simple use-cases, native performance.
○​ Cons: Harder to validate or control state.

function UncontrolledInput() {
const inputRef = useRef();
const handleClick = () => {
alert(inputRef.current.value);
};
return (
<>
<input ref={inputRef} type="text" />
<button onClick={handleClick}>Show Value</button>
</>
);

●​ }

2. Input Handling with State


Use a piece of state per input or a single state object for multiple fields.​
function SignupForm() {
const [form, setForm] = useState({ username: '', email: '' });

const handleChange = e => {


const { name, value } = e.target;
setForm(prev => ({ ...prev, [name]: value }));
};

return (
<form>
<input
name="username"
value={form.username}
onChange={handleChange}
/>
<input
name="email"
type="email"
value={form.email}
onChange={handleChange}
/>
</form>
);

●​ }

3. Handling Different Input Types


Text Input:​
<input
type="text"
value={text}
onChange={e => setText(e.target.value)}

●​ />

Radio Buttons:​
function GenderSelector() {
const [gender, setGender] = useState('male');
return [
['male', 'Male'],
['female', 'Female'],
].map(([value, label]) => (
<label key={value}>
<input
type="radio"
name="gender"
value={value}
checked={gender === value}
onChange={e => setGender(e.target.value)}
/>
{label}
</label>
));

●​ }

Checkbox:​
<label>
<input
type="checkbox"
checked={isChecked}
onChange={e => setIsChecked(e.target.checked)}
/>
Accept Terms

●​ </label>

Textarea:​
<textarea
value={textArea}
onChange={e => setTextArea(e.target.value)}

●​ />

Select Dropdown:​
<select value={option} onChange={e => setOption(e.target.value)}>
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="cherry">Cherry</option>

●​ </select>

4. Form Submission Logic


Handling Submit: Use onSubmit on the <form> element and call
e.preventDefault().​
function ContactForm() {
const [form, setForm] = useState({ name: '', message: '' });

const handleSubmit = e => {


e.preventDefault();
// Validate
if (!form.name || !form.message) {
alert('All fields required');
return;
}
// Send data
console.log('Submitting', form);
// Reset
setForm({ name: '', message: '' });
};

return (
<form onSubmit={handleSubmit}>
{/* inputs... */}
<button type="submit">Send</button>
</form>
);

●​ }
●​ Validation & Feedback: Show error messages or disable submit until valid.​
<button type="submit" disabled={!form.name}>Submit</button>

End of Module: Forms in React

You might also like