React PDF
React PDF
👍
React Notes
🔴
This Notes Divide into Four Parts
🔴
Fundamental.
🔴
Intermediate.
🔴
Advanced.
Professional Dev.
🔴 Fundamental. ➖
Building Your First React App
1. Tools Used:
○ CodeSandbox: An online code editor for React apps. Access it via
codesandbox.io or directly at react.new.
2. Steps to Create the App:
○ Open App.js, delete existing content, and start from scratch.
Define a React component using a function:
jsx
Copy code
function App() {
return (
<div>
<h1>Hello World!</h1>
<button>Get advice</button>
</div>
);
}
export default App;
○
○ Save and see updates in the preview.
3. Fetching Data:
○ Use fetch() to retrieve advice from the API: https://api.adviceslip.com/advice.
○ Handle response data using async/await.
4. React State:
Use useState to store and update data dynamically.
Jsx
const [advice, setAdvice] = useState("");
○
○ Update state with setAdvice after fetching advice.
5. Dynamic Updates:
Use onClick on the button to trigger the getAdvice function:
jsx
<button onClick={getAdvice}>Get advice</button>
○
6. Display State:
Use curly braces {} in JSX to display dynamic values:
jsx
<p>{advice}</p>
○
7. Using Effects:
Use useEffect to fetch advice when the app loads:
jsx
useEffect(() => {
getAdvice();
}, []);
○
8. Count Clicks:
Create another useState for counting button clicks:
jsx
const [count, setCount] = useState(0);
setCount((prevCount) => prevCount + 1);
○
9. Creating Components:
Break UI into reusable components, e.g., a Message component for the count:
jsx
function Message({ count }) {
return <p>You have read {count} pieces of advice.</p>;
}
○
10.Props:
Pass data to components using props:
jsx
<Message count={count} />
○
11.Key React Concepts Covered:
○ JSX: HTML-like syntax for UI.
○ State: For dynamic updates.
○ Props: Passing data to components.
○ Effects: For side-effects like fetching data.
○ Components: Reusable pieces of UI.
12.Summary:
○ A simple app to fetch and display advice.
○ Core React features: state, props, effects, and components.
○ Dynamic UI updates based on state changes.
○
This lecture provides a comprehensive explanation of why modern front-end frameworks,
like React, exist and why they are essential in today's web development. Here's a
structured summary and key takeaways:
Key Insight
This foundation sets the stage to dive into how React works and
why it’s uniquely powerful for building SPAs!
● React’s Advantage:
○ Handles UI and state synchronization seamlessly.
○ Reduces manual DOM manipulation and potential bugs.
○ Simplifies code, especially for complex applications.
● When to Use Vanilla JS:
○ Suitable for small, simple apps where manual DOM
manipulation is manageable.
○ For more complex apps, React provides better scalability
and maintainability.
Main Takeaway
Overview of React
What is React?
1. Adoption:
○ Used by major companies like Facebook, Instagram, and
others.
○ High demand for React developers in the job market.
2.Community:
○ A large and active developer community.
○ Extensive tutorials, Q&A support, and third-party libraries.
3.Performance:
○ Efficient updates through the virtual DOM.
○ React "reacts" to state changes, ensuring smooth UI
interactions.
React’s Impact
JavaScript Destructuring
1. Introduction to Destructuring
javascript
console.log(title, author);
● Key Points:
○ The variable names must match the object property
names.
○ Order does not matter in object destructuring.
Benefits:
javascript
4. Array Destructuring
console.log(primaryGenre, secondaryGenre); //
Outputs: Sci-Fi, Humor
● Key Points:
○ The first variable matches the first element of the array, the
second variable matches the second element, and so on.
○ Order does matter in array destructuring.
Skipping Elements:
● APIs:
Destructure response objects to directly access specific
properties.
6. Summary
● Key Points:
○ The rest operator must always be the last element in the
destructuring pattern.
○ It collects all leftover values into an array.
Usage with Objects:
console.log(otherDetails); // Remaining
properties in an object
2. Spread Operator (...)
For instance:
const updatedBook = { pages: 1000, ...book };
// book.pages overrides 1000
● Arrays:
○ Combine datasets: const allGenres =
[...genres1, ...genres2];
○ Clone arrays: const clonedGenres = [...genres];
● Objects:
○ Clone objects: const clonedBook = { ...book };
Merge objects:
const completeBook = { ...book, ...extraDetails
};
● React Usage (Preview):
javascript
You want to take the first two colors, but keep the rest of the
crayons in another box.
console.log(firstColor); // "Red"
console.log(secondColor); // "Blue"
Now, you want to create a new box with the same crayons, but add
a new color called "Orange."
javascript
Explanation:
● The ...crayons is like saying: "Take all the crayons out of the
first box and spread them into the new box."
● Then, you simply add "Orange" to the end.
Simple Summary:
Here’s how you can do it in the old way and the new arrow function
way
Old Way (Traditional Function):
function getYear(dateString) {
return dateString.split("-")[0];
console.log(getYear("2024-12-10")); // Output:
2024
console.log(getYear("2024-12-10")); // Output:
2024
console.log(message);
Summary:
Syntax:
javascript
Example:
Regular Function:
javascript
function add(a, b) {
return a + b;
}
Arrow Function:
javascript
Key Points:
const result = a * b;
return result;
};
Logical operators like && (AND) and || (OR) have a cool feature
called short-circuiting, which means they sometimes stop
checking values early and return a result. Let's break this down
simply!
2. OR (||) Operator
● Why? If the first value is true, it doesn’t matter what the second
value is because OR needs only one value to be true.
You can use || to set default values if the first value is falsy (e.g.,
false, 0, "", null, undefined).
Example:
javascript
const name = "" || "Default Name"; // Output:
"Default Name"
Summary:
● Use && when you want to check if both conditions are true.
● Use || to provide a default, but be careful with 0 or "".
● Use ?? if you want to handle only null or undefined.
These tricks are super useful for clean and smart code! 😊
The optional chaining operator (?.) helps you avoid errors when
accessing properties of objects that might not exist. It's a great
tool to safely handle situations where some data might be
undefined or null. Let’s simplify it with examples.
const book = {
reviews: {
Goodreads: {
reviewsCount: 200,
},
},
};
Here:
Use ?. whenever:
javascript
if (book.reviews && book.reviews.libraryanything)
{
console.log(book.reviews.libraryanything.review
sCount);
}
javascript
console.log(book.reviews.libraryanything?.reviews
Count);
5. Full Example
Let’s calculate the total reviews from two sources (Goodreads and
libraryanything):
javascript
function getTotalReviewCount(book) {
const goodreadsCount =
book.reviews.Goodreads?.reviewsCount ?? 0;
const libraryanythingCount =
book.reviews.libraryanything?.reviewsCount ??
0;
return goodreadsCount + libraryanythingCount;
}
// Test cases
const book1 = {
reviews: {
Goodreads: { reviewsCount: 200 },
libraryanything: { reviewsCount: 50 },
},
};
const book2 = {
reviews: {
Goodreads: { reviewsCount: 300 },
},
};
console.log(getTotalReviewCount(book1)); //
Output: 250
console.log(getTotalReviewCount(book2)); //
Output: 300
Summary:
😊
Optional chaining saves time, avoids errors, and keeps your code
clean!
Imagine you have a box of toys, but sometimes the box is empty.
You want to find out if there’s a car toy inside without breaking
the box.
You open the box, then look inside for the car.
javascript
Copy code
const toyBox = {}; // The box is empty!
console.log(toyBox.car.type);
// ERROR! You tried to check the `type` of a car
that doesn’t exist.
javascript
const toyBox = {}; // The box is empty!
console.log(toyBox.car?.type);
// Output: undefined (No error! The box is empty,
and there’s no car.)
javascript
const toyBox = {
car: { type: "red sports car" },
};
console.log(toyBox.car?.type);
// Output: "red sports car" (It safely found the
car!)
Simple Explanation:
You have a basket of apples, and each apple has a sticker with its
weight written on it. You want to make a list of just the weights
from all the apples.
The map Method in Action:
javascript
const apples = [
{ color: "red", weight: 150 },
{ color: "green", weight: 130 },
{ color: "yellow", weight: 170 },
];
Now, you want a new array with only the weights of these apples.
javascript
const weights = [];
for (let apple of apples) {
weights.push(apple.weight);
}
javascript
const weights = apples.map(apple =>
apple.weight);
Simple Explanation:
For example:
If you have numbers [1, 2, 3] and want to double them, you
can use map like this:
javascript
const numbers = [1, 2, 3];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6]
Think of map as a tool that "transforms" each item in the array!
Simple Example:
Imagine you have a basket of fruits, and you only want the apples.
javascript
const fruits = ['apple', 'banana', 'orange',
'apple', 'grape'];
const apples = fruits.filter(fruit => fruit ===
'apple');
console.log(apples); // ['apple', 'apple']
Here, the filter checks each fruit, and if it's an "apple," it keeps it in
the new array.
Key Points:
1.Returns a new array: Only items that meet the condition are
included.
2.Does not change the original array.
3.Used to filter data, like finding books with more than 500 pages
or products in stock.
It's like a strainer that separates the items you want from the ones
you don't!
Sure! Let's say we want to find the total number of pages in a list
of books. Here's how we can do it using the reduce method,
explained like you're teaching a child:
Example:
javascript
const books = [
{ title: "Book 1", pages: 200 },
{ title: "Book 2", pages: 150 },
{ title: "Book 3", pages: 300 }
];
Explanation:
It's like going through a stack of books and adding their pages one
😊
by one until you know how many pages you'd need to read them
all.
Give another example
Example:
Imagine you went shopping and your cart has these items:
javascript
Copy code
const cart = [
{ item: "Apple", price: 2 },
{ item: "Banana", price: 1 },
{ item: "Milk", price: 3 }
];
Code:
javascript
Copy code
const totalPrice = cart.reduce((sum, product) =>
{
return sum + product.price; // Add the current
product's price to the sum
}, 0); // Start with 0 as the initial sum
console.log(totalPrice); // Output: 6
Explanation:
😊
This is like counting the money you'll need to pay for all the items,
one by one, until you know the final amount.
javascript
Copy code
javascript
Copy code
● What happens?
○ The sort method compares two numbers at a time (a and
b).
○ If a - b is:
■ Negative: a comes before b (smaller number first).
■ Positive: b comes before a.
■ Zero: The order doesn’t change.
Sorting in Descending Order:
javascript
Copy code
● What happens?
○ Now we subtract a from b. This flips the logic so bigger
numbers come first.
Key Points:
javascript
Copy code
const books = [
];
console.log(sortedBooks);
This way, you can use the sort method to organize arrays in
ascending or descending order based on any criteria.🎉
The sort method in JavaScript is used to
arrange the elements of an array in a specific
order, either ascending (smallest to largest) or
descending (largest to smallest).
● It works by comparing two elements at a time using a function
you provide.
● By default, it converts elements to strings and sorts them
alphabetically, but you can customize it to sort numbers or
objects.
For example:
javascript
console.log(ascending); // [1, 2, 5, 9]
Example:
javascript
console.log(updatedBooks);
Example:
javascript
// Delete book with id = 2
console.log(filteredBooks);
● Definition: Use the map method to create a new array with the
updated element while keeping others unchanged.
● Why: map keeps the array length the same, updating only the
specified element.
Example:
javascript
);
console.log(updatedBooksArray);
// Result: [{id: 1, title: "Updated Book 1"},
{id: 2, title: "Book 2"}]
**************************************
Summary:
Key Takeaways:
1.Clarity on .json():
○ Highlight that res.json() parses the response body into
a JavaScript object and why it returns a Promise.
2.Error Handling:
Demonstrate catch() to handle errors in the chain for a more
robust solution:
javascript
fetch('https://jsonplaceholder.typicode.com/tod
os')
.then((res) => {
return res.json();
})
○
3.Async/Await Alternative:
try {
console.log(data);
} catch (err) {
console.error('Error:', err);
fetchData();
○
4.Practical Examples:
○ Mention how the fetched data can be displayed or
processed further (e.g., rendering UI components in
React).
The Story:
Imagine you're at a pizza shop. You order a pizza (this is like calling
the fetch function).
● While the pizza is being baked (fetching data), you don’t just sit
there doing nothing! You might chat with a friend or play a game
on your phone (this is JavaScript running other lines of code).
● When the pizza is ready, the chef calls you and hands it over
(this is like the then() method handling the data when it’s
ready).
The Example:
javascript
console.log("Ordering a pizza...");
fetch('https://jsonplaceholder.typicode.com/todos
/1')
.then((response) => response.json()) // Wait
for the "pizza" to be ready
.then((data) => {
});
What Happens:
Ordering a pizza...
🍕
without stopping everything else—just like how you keep busy
while waiting for your pizza!
Async/Await in JavaScript
1. What is Async/Await?
○ A cleaner way to work with Promises.
○ Makes asynchronous code look like regular synchronous code.
2. How to Use Async/Await:
○ Use async before a function to make it an async function.
○ Use await inside the async function to pause code until a Promise
resolves.
Example Code:
javascript
async function getTodos() {
const response = await
fetch('https://jsonplaceholder.typicode.com/todos/1');
const data = await response.json();
console.log(data);
}
getTodos();
console.log("This runs before the data arrives.");
3.
○ What happens?
■ Fetch starts, JavaScript moves to the next line.
■ await pauses inside the getTodos function until data is fetched.
■ Console logs data after fetching but only inside the async
function.
4. Key Points to Remember:
○ await only works inside async functions.
Async functions always return a Promise.
javascript
const todos = getTodos(); // `todos` is a Promise, not the actual data.
○
○ To use the result outside, chain .then() or use another async
function.
Problem:
You try to return multiple elements in JSX, but React gives this
error:
Cause:
React doesn’t allow multiple sibling elements without wrapping
them in a single parent.
Solution:
Wrap the elements inside a <div> or a React Fragment.
Example Code:
Before (Error):
jsx
return (
<h1>Hello</h1>
<p>This is an error.</p>
);
After (Fixed):
jsx
return (
<div>
<h1>Hello</h1>
<p>This is fixed!</p>
</div>
);
jsx
return (
<>
<h1>Hello</h1>
<p>This is fixed!</p>
</>
);
Explanation for Kids:
Imagine you have two toys, and React says, "You can’t leave
😊
them loose; put them in a box first!" So, we wrap our toys
(elements) in a box (<div> or <>). Now React is happy!
React Components
1.What Are Components?
○ Components are the building blocks of any React app.
○ React apps are made entirely of components.
○ Each component:
■ Has its own data, logic, and appearance.
■ Renders a small piece of the user interface (UI).
2.Why Use Components?
○ They help build complex UIs by combining smaller
components like Lego pieces.
○ Components can be nested (placed inside one another).
○ Components can be reused, saving time and effort.
3.Component Relationships:
○ Components can have parent-child relationships:
■ A parent component contains one or more child
components.
4.Component Tree:
○ A diagram showing the hierarchy and relationships
between components.
○ Helps visualize how components are nested and
connected.
jsx
function Shop() {
return (
<div>
<FruitList />
</div>
);
}
function FruitList() {
return (
<div>
</div>
);
function FruitItem(props) {
return (
<div>
<p>{props.name} - {props.price}</p>
</div>
);
}
Explanation for Kids:
This way, we can reuse FruitItem for each fruit, making our work
faster and neater! 😊
JSX in React
1.What is JSX?
○ JSX is a special syntax used in React to describe how
components look and behave.
○ It looks like HTML, but it’s actually a mix of HTML, CSS,
and JavaScript.
○ Each React component must return one block of JSX to
define its appearance.
2.Why Use JSX?
○ JSX makes code easier to write and read compared to
using plain JavaScript functions.
○ React uses a tool called Babel to convert JSX into regular
JavaScript because browsers don’t understand JSX.
○ Behind the scenes, JSX becomes React.createElement
function calls to render HTML.
3.Declarative vs. Imperative:
○ Imperative (Vanilla JavaScript):
■ You tell the browser step-by-step what to do (e.g.,
select elements, update them manually).
■ Example: "Go to this button, change its text to
'Clicked'."
○ Declarative (React and JSX):
■ You tell React what the UI should look like, and React
figures out the rest.
■ Example: "Show this button text based on the data."
4.Benefits of JSX and Declarative Approach:
○ No need to manipulate the DOM directly (e.g., no
document.querySelector or addEventListener).
○ The UI is always in sync with the data (e.g., props and
state).
○ React handles the hard work of updating the UI for us.
javascript
● Here, we tell the browser exactly how to update the text when
the button is clicked.
function App() {
const [text, setText] = React.useState("Click me");
return (
<button onClick={() => setText("Clicked!")}>
{text}
</button>
);
}
● Here, we tell React what the button should show based on the
text variable.
● React automatically updates the button when the text changes.
😊
React with JSX is like showing the picture—it simplifies things and
lets React do the hard work for you!
Traditional Approach:
HTML file:
html
<button id="myButton">Click me</button>
●
CSS file:
css
#myButton {
background-color: blue;
color: white;
●
JavaScript file:
javascript
const button =
document.getElementById('myButton');
button.addEventListener('click', () => {
alert('Button clicked!');
});
●
● All logic, style, and UI are in different files.
React Approach:
jsx
function Button() {
return (
<button
>
Click me
</button>
);
● Traditional way: You keep the toy car in one box, its wheels in
another, and instructions in a third box.
● React way: You put the toy car, its wheels, and its instructions
all in one box.
😊
React makes it easier to find and work on one "toy" (or part of your
app).
Props in React
1.What are Props?
○ Props (short for properties) are used to pass data from a
parent component to a child component.
○ They allow communication between components and help
configure or customize child components.
○ Props are like arguments in JavaScript functions.
2.What Can We Pass as Props?
○ Any type of value:
■ Single values (e.g., numbers, strings).
■ Arrays, objects, functions, or even other React
components.
3.Props vs. State:
○ Props: Data from parent to child. Immutable (cannot be
changed by the child).
○ State: Internal component data that can change over
time.
4.Why Are Props Immutable?
○ React uses pure functions for components to avoid side
effects (unexpected changes to external data).
○ If props were mutable, changing them in a child would also
change the parent, creating bugs.
5.One-Way Data Flow:
○ Data flows from parent to child only (top to bottom).
○ This makes React apps predictable, easy to understand,
and debug.
Example: Greeting Component
jsx
function Greeting(props) {
function App() {
😊
component knows only what it’s told, just like following
instructions!
Rules of JSX
1.What is JSX?
○ JSX looks like HTML, but it works with JavaScript.
○ You can add JavaScript expressions in JSX by using
curly braces {}.
2.Allowed in JSX:
○ Variables, arrays, objects, operators (e.g., ternary ? :),
and loops (e.g., map).
3.Not Allowed in JSX:
○ Statements like if/else, for, or switch.
4.JSX Produces Expressions:
○ JSX creates JavaScript expressions that can be stored in
variables, passed to functions, or used in conditions.
○ Example: Assign JSX to a variable or use it in a conditional.
5.One Parent Rule:
○ JSX must have one root element (like a container).
○ To include multiple elements, wrap them in a React
Fragment (like <></>).
6.Differences from HTML:
○ Class → className
○ Inline styles → Use objects (e.g., style={{ color:
'red' }})
○ Self-closing tags required for empty elements (e.g., <img
/>).
jsx
function Greeting() {
return (
<div>
{message}
</div>
);
When people talk about "LEGO" outside of toys, they often mean:
😊
you can create something complex by putting together small,
reusable pieces.
javascript
const pizzaData = [
];
Rendering the List
javascript
function App() {
return (
<ul>
{pizzaData.map((pizza) => (
<li key={pizza.id}>{pizza.name}</li>
))}
</ul>
);
What Happens?
javascript
function App() {
return (
<>
<ul>
<li>Pizza 1</li>
<li>Pizza 2</li>
</ul>
</>
);
Output in DOM
html
<ul>
<li>Pizza 1</li>
<li>Pizza 2</li>
</ul>
function App() {
return (
<div>
<ul>
<li>Pizza 1</li>
<li>Pizza 2</li>
</ul>
</div>
);
html
<div>
<li>Pizza 1</li>
<li>Pizza 2</li>
</ul>
</div>
This extra <div> can mess up your layout, which fragments avoid.
Key Takeaway
😊
the DOM. Use them whenever you don’t want extra wrapper
elements in your HTML!
○
Example:
jsx
<span>{pizza.soldOut ? "SOLD OUT" :
`$${pizza.price}`}</span>
○
3.What is Conditional Class?
○ Add a class name conditionally to an element (e.g., to
make it look grayed out).
○
Example:
jsx
Copy code
<li className={`pizza ${pizza.soldOut ?
"sold-out" : ""}`}></li>
○
4.Benefits in React:
○ No need for manual DOM manipulation like in plain
JavaScript.
○ JSX makes it cleaner and declarative.
jsx
return (
</li>
);
// Example Data:
const pizza = { name: "Margherita", price: 10,
soldOut: true };
// Renders:
What Happens?
● If Sold Out:
○ The text will show "SOLD OUT."
○ The li will have the class pizza sold-out.
○ It will look grayed out.
● If Not Sold Out:
○ The text will show the price, e.g., $10.
○ The li will have the class pizza.
Key Takeaway
😊
conditions. Use ternary operators and template literals to keep
the code simple and clean.
React Basics Recap
1.Components
○ Building blocks of a React app.
○ Self-contained: includes data, logic, and appearance.
○ Return JSX to describe what users see on the screen.
2.JSX
○ Combines HTML, CSS (via style prop), and JavaScript
(inside {} curly braces).
○ Declarative: describes what the UI should look like.
3.Component Tree
○ Components are organized into a tree:
■ Parent Component: Uses/includes other
components.
■ Child Component: Used by its parent.
○ Example: App → Header, Menu, Footer → Pizza Items,
Order.
4.Props
○ Pass data from parent to child components.
○ Props are read-only (cannot mutate them).
○ Example: Pass different pizza objects to a Pizza
component.
○ Data flows downward only (parent → child).
5.Lists
○ Render multiple components by looping through arrays
using the map() method.
○ Example: Create a pizza list from an array of pizza objects.
6.Conditional Rendering
○ Render components based on conditions:
■ Use &&, ternary operators, or multiple returns.
○ Example: Show "Sold Out" text if a pizza is unavailable.
7.Key Theoretical Concepts
○ Imperative vs Declarative: React focuses on declarative
code.
○ Separation of Concerns: Keep logic, data, and UI
structured.
○ Props Immutability: Props should not be changed.
Key Takeaways
😊
props, lists, and conditional rendering—all while leveraging
JavaScript skills you already know!
Let’s build a simple button that keeps track of how many times it’s
clicked. This is a perfect example of using state in React.
Code:
Javascript
import React, { useState } from 'react';
function Counter() {
};
return (
<div>
<button onClick={handleClick}>Click
me!</button>
</div>
);
😊
That’s how state works—just like keeping track of something
important in a notebook and showing it when needed!
Key Takeaway
Key Takeaway
Key Takeaway
1.React is Declarative
○ React does not manipulate the DOM directly.
○ Instead, it re-renders components when data changes.
2.Re-Rendering
○ React calls the component function again to update the
view.
○ This creates a new version of the component.
○ React keeps the state intact during re-renders (unless the
component is removed).
3.State Updates Trigger Re-Rendering
○ State changes (using setState from useState)
automatically re-render the component.
○ Example: Clicking a button updates state, and React
updates the view.
4.Example: Advice App
○ Click button → Fetch new advice → Update state →
React re-renders view.
○ Example advice: Old view shows "Stay consistent", new
state updates to "Quality beats quantity".
5.Why is it called React?
○ React reacts to state changes by updating the user
interface automatically.
Key Takeaway
To update a component's view, update its state. React handles the
rest by re-rendering and keeping the UI in sync with the data.
Key Takeaway
1.State
○ Internal data owned by the component.
○ Acts as the component's memory (persists across
re-renders).
○ Can be updated by the component itself.
○ Updating state causes a re-render.
○ Used to make components interactive.
2.Props
○ External data passed from parent to child components.
○ Similar to function parameters.
○ Read-only: Cannot be modified by the receiving
component.
○ Re-render occurs if props are updated by the parent.
○ Used to configure child components (like settings).
3.Connection Between State and Props
○ If state is passed as a prop:
■ Updating the state causes both parent and child
components to re-render.
■ Ensures the child component stays in sync with the
state.
Key Takeaway
1.State in React:
○ State is the most important concept in React, representing
data that changes during the app's lifecycle.
○ useState is used to create and manage state in React
components.
2.What is State Management?
○ Deciding when to create state, what type of state is
needed, where to place it, and how data flows in the app.
○ Think of state management as giving each piece of state a
"home" in your code.
3.Types of State:
○ Local State: Used in a single component or passed to its
child components (e.g., search bar input).
○ Global State: Shared across multiple components (e.g.,
shopping cart data). Use tools like React Context API or
Redux for global state.
4.Key Guideline:
○ Start with local state and move to global state only if
absolutely necessary.
5.When to Create State:
○ Static Data: If the data doesn’t change, use a regular
variable (e.g., const).
○ Derived State: If new data can be computed from existing
state or props, derive it instead of creating new state.
○ useRef: Use for data that doesn’t need to trigger
re-renders but persists over time.
○ New State: Use useState when the data changes and
should re-render the component.
6.Where to Place State:
○ Single Component: Place state in the component that
uses it.
○ Child Component: Pass state via props if needed by a
child component.
○ Sibling or Parent Components: Move state to the first
common parent (this is called lifting state up).
○ Global: Use global state if needed by many components
across the app.
7.Decision Flow Summary:
○ Is the data static? → Use a variable.
○ Can it be derived? → Compute it from existing state/props.
○ Does it need to re-render? → Use useState.
○ Where is it needed? → Place it locally, lift it up, or make it
global.
8.Practice and Intuition:
○ Over time, deciding when and where to create/lift/derive
state becomes intuitive. Use flow charts or guides at the
start to help.
Key Concepts to Remember: Local state, lifting state up, derived
state, global state, Context API, Redux.
○
○
4.Why Move State to Parent Component:
○ items are needed in the PackingList component (for
rendering).
○ State can’t flow sideways or upward; move items state to
the common parent (App component).
5.Passing State and Functions as Props:
○
○
6.Lifting State Up:
○ Definition: Moving state to the closest common parent
component so sibling components can share it.
○ Steps:
1.Identify common parent.
2.Move state to the parent.
3.Pass state and functions as props to children.
7.Summary:
○ Form Component: Creates new items and calls
onAddItems to update the state.
○ PackingList Component: Renders the items passed
from the parent.
○ App Component: Holds items state and updates it via
handleAddItems.
Key Concept
Problem:
● You: "I need to know how many candies are in the bowl!"
● Sibling: "Me too! But I also need to tell the bowl when I take
one."
● How can both of you share the candy count and update it at the
same time?
Solution:
In React Terms:
Code Example:
jsx
function Bowl() {
const [candies, setCandies] =
React.useState(10); // Parent keeps count
return (
<div>
<p>Number of candies: {candies}</p> {/*
Share count */}
<Child takeCandy={takeCandy} />
<Sibling takeCandy={takeCandy} />
</div>
);
}
Simple Takeaway:
🔴 Intermediate 👍
1.Stateless/Presentational Components:
○ Definition: Components with no state.
○ Purpose: Simply receive props and display data or
content.
○ Examples: Logo, number of results, individual movie
cards.
○ Characteristics: Often small and reusable.
2.Stateful Components:
○ Definition: Components that manage their own state.
○ Purpose: Handle dynamic data and interactions.
○ Examples: Search bar with input state.
○ Characteristics: Can still be reusable despite having state.
3.Structural Components:
○ Definition: Components responsible for the structure of the
app.
○ Purpose: Act as pages, layouts, or screens by composing
smaller components.
○ Examples: A homepage layout or dashboard screen.
○ Characteristics: Can be large and non-reusable or small
and reusable.
○ Common in large apps: Provide structure as apps grow in
complexity.
Key Point:
These categories emerge naturally—don’t force components into
them. They serve as a helpful way to think about and organize
your code as your app evolves.
Imagine you have a toy that your little brother wants. But, instead
of giving it directly to him, you pass it to your sister, who passes
it to your cousin, and then finally, it reaches your little brother.
Your sister and cousin don’t even want the toy—they’re just
helping to pass it along. This extra passing around is like prop
drilling.
React Example:
jsx
function App() {
const message = "Hello from App!"; // The toy
(data)
The Context API in React can help by letting the GrandChild get
the data directly from App, skipping the middle components.
1.Components:
○ A blueprint or template describing a part of the UI.
○ Written as a JavaScript function that returns React
elements (using JSX).
2.Component Instances:
○ Created whenever a component is used in code.
○ Each instance:
■ Has its own state, props, and lifecycle.
■ Exists as part of the component tree.
3.React Elements:
○ The result of calling a component function.
○ A big immutable object stored in memory.
○ Contains all the info needed to create DOM elements.
4.DOM Elements:
○ The final, visual representation of components on the
browser.
○ React elements are converted into DOM elements during
rendering.
5.Key Concept:
○ Component = Blueprint
○ Instance = Actual copy with state and props
○ React Element = Info needed for rendering
○ DOM Element = Visible output in the browser
🚀
This flow: Component → Instances → React Elements → DOM
Elements helps React create and update the UI efficiently!
🚀
Understanding this process helps us know how React efficiently
manages UI updates!
1.Initial State
○ You have a button and a modal (a popup window).
○ The modal is hidden (showModal = false).
2.State Update
○ You click the button, changing showModal to true.
3.Render Phase
○ React creates a new virtual DOM:
■ Adds the modal component.
○ Compares with the old Fiber tree:
■ Notices the modal is new and adds it to the effects
list.
4.Commit Phase
○ React updates the actual DOM to show the modal on the
screen.
🚀
Think of React as a super-smart LEGO builder who only changes
the blocks that need updating, saving time and energy!
State Update Batching in React
1. What is Batching?
●
5. React 18 and Beyond
●
7. Why Batching Matters
Events in React
1. Event Propagation in the DOM
● React events work with the DOM tree, not the React component
tree.
● Synthetic events like focus, blur, and change bubble in React
(unlike in native DOM).
● scroll events do not bubble in React.
● Library:
○ Provides specific tools (e.g., React is for building UI
components).
○ Developers choose additional tools/libraries (e.g., routing,
state management).
○ Offers freedom but requires decision-making.
● Framework:
○ All-in-one solution (e.g., Angular, Vue).
○ Includes routing, state management, styling, etc., out of the
box.
○ Less freedom but faster setup and fewer decisions.
2. React Ecosystem
By learning React, you gain the skills to build apps with either just
React or with frameworks for more advanced use cases.
Key Takeaways from React Section
1. Components and Instances
Take time to review and let these key points sink in before moving
to the next section!
Component Lifecycle
1. What is Component Lifecycle?
● You can run specific code during each phase using the
useEffect hook.
● Useful for tasks like:
○ Fetching data.
○ Cleaning up resources.
● A list of state variables and props that the effect depends on.
● React re-executes the effect when any dependency changes.
3. Key Rules
● Include all state and props used in the effect in the array.
● Missing dependencies cause bugs (e.g., stale closures).
4. Types of Dependency Arrays
function TimerComponent() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
// Start the timer
const timer = setInterval(() => {
setSeconds((prev) => prev + 1);
}, 1000);
1.What’s Happening?
○ When the component loads, we start a timer that adds 1
second every second.
○ If the user closes the page or goes to another screen, we
don’t want the timer to keep running.
2.How Do We Stop the Timer?
○ Inside the useEffect, we return a cleanup function:
clearInterval(timer).
○ This cleanup tells React, “Hey, stop the timer when the user
leaves this component.”
3.Why is Cleanup Important?
○ Without the cleanup, the timer keeps running forever in the
background, wasting memory and causing bugs.
○ The cleanup makes sure everything is tidy when the
component is no longer needed.
4.Fun Analogy for a Child:
○ Imagine you’re playing with a toy (timer).
○ When it’s bedtime (leaving the component), you put the toy
😊
back in the box (cleanup) so it doesn’t make noise at night!
1.What Happens?
○ When you press the Escape key, the handleKeyDown
function checks if it’s the Escape key.
○ If yes, it calls onCloseMovie to close the movie details.
2.Why Cleanup?
○ Imagine stacking blocks each time you mount the
component. Without cleanup, the blocks pile up endlessly.
Cleanup removes the extra blocks, keeping it neat.
3.Child-Friendly Analogy:
○ Adding an event listener is like ringing a doorbell to get
attention.
○ Cleanup is like unplugging the doorbell when you don’t
need it anymore, so it doesn’t keep ringing by mistake!
Deep Dive into React Hooks
1.Hooks Overview:
○ Hooks are easy to start with but take time to master.
○ A strong understanding is essential for React developers.
2.What We'll Learn:
○ Rules of Hooks: Why they exist and how to follow them.
○ useState: Explore it further for managing state.
○ useRef: Learn its purpose and usage.
○ Custom Hooks: Create our own reusable Hooks.
3.useEffect:
○ Won't revisit in this section but will explore later.
4.Goal:
○ Build a solid foundation in Hooks while finishing the project.
Example:
javascript
import { useState, useEffect } from "react";
function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
async function fetchData() {
const response = await fetch(url);
const result = await response.json();
setData(result);
setLoading(false);
}
fetchData();
}, [url]);
Usage:
javascript
function App() {
const { data, loading } =
useFetch("https://api.example.com/data");
🔴 Advanced.
useRef Hook
1. What is useRef?
○ Creates a ref (reference), a mutable object with a current property.
○ The current property can hold any value and persists across renders.
2. Use Cases for useRef
○ Store variables that stay the same between renders (e.g., previous state,
setTimeout IDs).
○ Select and store DOM elements.
3. Key Characteristics
○ Refs do not cause re-renders when updated.
○ Usually used for data not part of the visual output (e.g., in event handlers or
effects).
○ Refs are mutable, unlike state, which is immutable.
4. State vs. Ref
○ State: Causes re-renders when updated.
○ Ref: Does not trigger re-renders; only remembers data.
○ State updates are asynchronous, while ref updates are immediate.
5. When to Use useRef
○ Use state for data that should re-render the UI.
○ Use ref for data to persist between renders but not re-render the UI.
6. Best Practices
○ Avoid using refs in render logic to prevent side effects.
○ Perform ref mutations inside useEffect or event handlers.
Imagine you’re playing a game, and you press a button to start a timer. You want to
remember the timer so you can stop it later. This is where we use useRef because it
can "hold" the timer for us without affecting the game screen (UI).
Code Example:
javascript
function Timer() {
const timerRef = useRef(null); // Create a box to hold the timer
ID
return (
<div>
<button onClick={startTimer}>Start Timer</button>
<button onClick={stopTimer}>Stop Timer</button>
</div>
);
}
😊
It’s like keeping your game tools in a drawer—they don’t need to be on the table all the time,
but you know where to find them when you need them!
😊
○ Come back later if your job requires understanding class components.
It’s a look into React’s past but not a priority for learning modern React!
Conclusion: Function components are the future of React, but class components are still
important for understanding older codebases!
4. Important Notes
● Class-based lifecycle methods can spread logic across multiple methods, making
them harder to maintain compared to hooks.
● Lifecycle methods are useful for understanding and working with older codebases.
5. Practice Suggestion
● Convert the example app from class components to function components using hooks
(useEffect, useState).
● Share your implementation to improve understanding.
Imagine you have a toy car.
Sometimes you want to:
In React, class components are like that toy car: they need special steps to handle these
things. We use lifecycle methods to know what’s happening and what to do.
○ This runs when the app loads for the first time.
○ It’s like opening your toy box and picking the car to play with.
○ Example: We can fetch weather data when the app starts.
js
Copy code
componentDidMount() {
fetchWeather(); // Get the weather when the app loads.
}
○ This runs whenever you change something in the app, like typing a new city
name.
○ It’s like adding stickers to your toy car to make it look cooler.
○ Example: Fetch new weather data when the city name changes.
js
Copy code
componentDidUpdate(prevProps, prevState) {
if (prevState.city !== this.state.city) {
fetchWeather(); // Fetch weather only if the city changed.
}
}
○ This runs when you close the app or stop using something.
○ It’s like turning off your toy car and putting it back in the toy box.
○ Example: Clean up timers or stop any leftover tasks.
js
componentWillUnmount() {
clearTimer(); // Clean up anything we don’t need.
}
Key Takeaway:
🚀
You’ll learn state management and performance optimization by working on exciting
projects.
● Ideal for simple, independent state (e.g., numbers, strings, arrays, or basic objects).
● State updates happen directly via setState.
● Updates feel imperative, making it easier to understand and use.
● Best for components with fewer pieces of state.
How to Choose
Key Takeaways
Key Takeaways
Key Takeaways
● Open/closed panels.
● Filters and sorting orders.
● Specific page data (e.g., city details).
● Params:
○ Send data directly via the URL for page-specific content.
○ Example: /cities/Lisbon → Displays Lisbon details.
● Query Strings:
○ Store additional state (e.g., map coordinates).
○ Example: /cities/Lisbon?lat=40&lng=-3.
Key Takeaways
● A system to pass data through the component tree without prop drilling.
● Allows components to share global state directly without passing props.
● Solves the prop drilling problem, where passing props through multiple levels
becomes cumbersome.
● Makes state accessible to deeply nested components directly.
1. Provider:
○ Shares a value (data) with all child components.
○ Usually placed at the top of the component tree.
○ value can include state variables and functions.
2. Consumer:
○ Components that read the value from the context.
○ Can be many consumers for a single provider.
How It Works
● Value Updates:
When the provider's value changes, all consumers using that context re-render
automatically.
● Re-rendering Rule:
Context updates cause subscribed components to re-render, similar to how state
updates work.
Benefits
Key Takeaway
The Context API is a powerful tool for managing state in a React app, especially for avoiding
prop drilling and making global state easily accessible.
In React, the parent is like the Provider, the board is the Context, and the children are
Consumers.
Code Example:
We’ll create an app where the favorite color is shared with child components.
jsx
function Parent() {
// 2. The parent's favorite color (state)
const [favoriteColor, setFavoriteColor] = useState("Blue");
return (
// 3. Provide the favorite color to all children
<ColorContext.Provider value={favoriteColor}>
<h1>Parent's Favorite Color: {favoriteColor}</h1>
<Child />
<OtherChild />
</ColorContext.Provider>
);
}
function Child() {
// 4. Use the favorite color (read from the board)
const color = useContext(ColorContext);
Output:
🎨
This way, the parent shares their favorite color with all children without telling them directly.
Tip: Understand state needs (local/global, UI/remote) to choose the right tool. Use the Context
API for UI state, and libraries for complex global or remote state.
Tip: Pay attention to how components re-render and the role of dependencies in useEffect.
This section is about making React apps both efficient and professional
Takeaway: Use memo selectively to optimize performance by reducing unnecessary renders for
slow, frequently re-rendered components with stable props.
useMemo and useCallback ➖
1. Issue with Memoized Components
○ Functions and objects are recreated on every render.
○ Even if they look identical, they are treated as new props.
○ This causes memo to fail as it sees the props as "changed."
2. Solution: Stabilize Props
○ Use useMemo to memoize values (e.g., objects).
○ Use useCallback to memoize functions.
3. How useMemo and useCallback Work
○ Both return cached values if dependencies stay the same.
○ If dependencies change, the value or function is recreated.
○ Dependencies are passed in an array, similar to useEffect.
4. Main Use Cases
○ Stabilize objects or functions passed as props to prevent wasted renders.
○ Avoid expensive recalculations by caching results of computations.
○ Prevent infinite loops in hooks like useEffect by memoizing dependencies.
5. When Not to Use
○ Avoid overusing these hooks.
○ Use them only for performance-critical scenarios.
Key Idea: Memoization with useMemo and useCallback improves performance by stabilizing
values or functions across renders and reducing unnecessary calculations.
3. React Guarantees
● User Events:
○ Handle clicks/keystrokes with event handlers, not effects.
● Data Fetching:
○ For larger apps, use libraries like React Query instead of useEffect.
● Synchronizing State:
○ Avoid setting state based on other states inside effects. Use derived state or
event handlers instead.
5. General Advice
Introduction to Redux
1. What is Redux?
2. Learning Steps
3. Why Redux?
Redux can seem tough but is straightforward and fun to learn with the right approach! 🎉
Understanding Redux
1. What is Redux?
4. Advanced Features
7. Redux Cycle
Bank Analogy:
● You (action creator) give instructions (action) to the bank teller (dispatcher).
● The teller updates the vault (store), not you directly.
🚀
Redux simplifies state logic by separating it from the rest of the app. With practice, it becomes
clear and manageable!
Redux Middleware
1. What is Middleware?
● Middleware is a function in Redux that sits between dispatching an action and the
reducer.
● It allows running custom logic (like API calls) before the action reaches the reducer.
2. Why Middleware?
3. Uses of Middleware
4. Thunk Middleware
6. Key Benefits
Middleware is essential for handling side effects and enhancing Redux functionality! 🚀
Redux Dev Tools
1. What are Redux Dev Tools?
2. Setup Steps
3. Features
4. Finding Bugs
5. Use Cases
3. Key Features
1. Immer:
○ Lets you write reducers as if mutating state directly.
○ Handles nested objects and arrays more easily.
2. Automatic Action Creators:
○ Creates action creators based on reducers.
3. Built-in Middleware Setup:
○ Automatically configures Thunk middleware.
○ Dev tools are pre-configured.
4. Compatibility
● Classic Redux and Redux Toolkit can coexist in the same app.
5. Biggest Advantage
● Simplifies Complex Code: Makes Redux easier and faster to implement for real-world
projects.
Redux vs. Context API
Context API + useReducer
Advantages:
Disadvantages:
● Repeating setup for multiple state slices can cause "provider hell."
● No built-in async handling (needs custom solutions).
● Performance optimization requires extra effort.
● Limited DevTools (basic React developer tools).
Redux
Advantages:
Disadvantages:
Recommendations
Key Takeaway
Choose the right tool based on your project's needs, not trends. Context is great for small-scale
state needs, while Redux shines in large-scale, complex apps.
Part 4 - Professional React Development {2-Project}
Focus of Part 4
Tools Used
● React Query
● Supabase
● Tailwind CSS
Features in Projects
● Authentication.
● Data filtering and pagination.
● Beautiful charts.
● Dark mode and context menus.
● Modals and more.
Outcome
Focus
Outcome
Planning Steps
1. Requirements:
○ Simple app for pizza ordering.
○ Features include menu display, cart, order placement, and tracking.
2. Feature Categories:
○ User: Input name for app access.
○ Menu: Load and display pizzas from API.
○ Cart: Add/update pizzas for order.
○ Order: Place and track orders.
3. Pages:
○ Home: Input user name.
○ Menu: Display pizzas.
○ Cart: Manage selected items.
○ New Order: Place orders.
○ Order Lookup: Check order status with ID.
4. State Management:
○ User & Cart: Global UI state (local in app).
○ Menu & Order: Global remote state (from API).
Tech Stack
3. Setup
4. Skipping
● If not interested, you can skip this section and continue with the project.
5. Next Steps
● After learning Tailwind basics, you will use it to style the components in your app.
Conclusion
Next Steps
● Style your project entirely with Tailwind CSS in the upcoming lessons.
Beginner Topics
●
● Use PostCSS or frameworks like Next.js for integration.
3. Responsive Design
Example:
html
<div class="text-base md:text-lg lg:text-xl">Responsive
Text</div>
●
Example:
html
<button class="bg-blue-500 hover:bg-blue-700 text-white">Hover
Me</button>
●
Intermediate Topics
1. Customization
●
● Override spacing, typography, or other default values.
2. Plugins
●
3. Dark Mode
Enable dark mode in configuration:
js
module.exports = {
darkMode: 'class', // or 'media'
};
●
●
4. Combining Classes
Use multiple utilities together:
html
<div class="flex items-center justify-center h-screen
bg-gray-200">
Centered Content
</div>
●
Advanced Topics
●
●
3. Custom Components
Build custom components using utility classes:
html
<div class="card p-6 bg-white shadow-md rounded-lg">
Custom Component
</div>
●
4. Advanced Animations
Use transition, duration, and ease utilities:
html
<button class="bg-blue-500 hover:bg-blue-700 transition-all
duration-300">
Animated Button
</button>
●
Example in React:
jsx
<button className="bg-green-500 text-white px-4 py-2">React
Button</button>
●
6. Advanced Configurations
● Add custom variants or themes.
Best Practices
Definition: Setting up Tailwind CSS involves configuring your project with the Tailwind
framework, enabling you to use its utility-first classes for styling.
Example:
Example:
3. Styling Text
Definition: Tailwind offers utilities for styling text, such as font size, weight, alignment, and
decoration.
Example:
Definition: Tailwind allows precise control over margins, padding, borders, and display
properties using intuitive utility classes.
Example:
5. Responsive Design
Definition: Tailwind's responsive utilities allow you to build designs that adapt to different
screen sizes effortlessly.
Example:
Definition: Tailwind simplifies working with Flexbox, making it easy to align and distribute
elements.
Example:
</div>
Definition: Tailwind's grid utilities help create complex layouts with minimal effort.
Example:
<div>1</div>
<div>2</div>
<div>3</div>
</div>
Definition: Tailwind makes it simple to style buttons and add hover, focus, and active states,
along with smooth transitions.
Example:
Click Me
</button>
Definition: Tailwind provides utilities to style input fields, checkboxes, radio buttons, and other
form elements.
Example:
Definition: The @apply directive in Tailwind allows you to reuse multiple utility classes in your
custom CSS.
Example:
/* custom.css */
.btn {
Definition: React components can encapsulate reusable Tailwind styles, making your UI
consistent and modular.
Example:
);
Definition: Tailwind simplifies positioning and layering with utilities for absolute, relative, and
fixed positioning, as well as z-index.
Example:
<div class="relative">
</div>
Definition: Tailwind allows customization of the default theme, such as adding custom fonts.
Example:
// tailwind.config.js
module.exports = {
theme: {
extend: {
fontFamily: {
},
},
},
};
Example:
</ul>
</nav>
Definition: Tailwind can be used to style a cart layout with items and totals dynamically
displayed.
Example:
<span>Pizza</span>
<span>$10</span>
</div>
</div>
Example:
<form class="space-y-4">
</form>
Definition: Display order details neatly with Tailwind's spacing, alignment, and typography
utilities.
Example:
</div>
Adding a Shopping Cart with Redux Toolkit
Prerequisite
Next Steps
Technologies Used
1. Frontend:
○ Styled Components: For component-based styling.
○ React Query: For efficient data fetching and caching.
○ React Hook Form: For handling forms easily.
○ React Router: Advanced routing and navigation.
2. Backend:
○ Superbase: Set up a backend and database from scratch.
Goal
Overview
In this section, you'll learn to create and manage a backend for your application using
Supabase.
● Learning Supabase equips you with essential tools for modern app development.
● A powerful step towards building complete, production-ready apps.
Benefits
Next Step
● Start building the backend for the Wild Oasis Management App using Supabase.
Technical Terms
● Primary Key: Unique identifier for a table (e.g., Guest ID in the guest table).
● Foreign Key: Field in one table that references the primary key of another table.
Next Steps
Next Steps
React Query will make the app development faster and easier! 🚀
React Query
What is React Query?
React Query is a powerful library for managing server-state (remote state) in React
applications. It simplifies fetching, caching, syncing, and updating server data, making it easier
to work with APIs and databases.
Important Concepts
1. Queries
○ Used to fetch and cache data.
Example:
const { data, error, isLoading } = useQuery('todos', fetchTodos);
2. Mutations
○ For creating, updating, or deleting data.
Example:
const mutation = useMutation(addTodo);
mutation.mutate(newTodo);
Best Practices
● Redux: Use Redux for client state and React Query for server state.
● Apollo Client: Similar functionality but React Query is API-agnostic and easier for
non-GraphQL APIs.
Highlights:
Note: This section is advanced but highly rewarding for boosting React expertise!
Key Takeaways:
● These patterns are not built into React but emerged as clever solutions to specific
problems.
● Mastering Render Props and Compound Components sets you apart as a React
developer.
● Learn and apply these patterns in practice for advanced React development.
Higher-Order Component (HOC) Pattern ➖
Key Concepts:
○ The HOC wraps the original component and adds new props or logic.
○ Example: A withToggles HOC adds toggle functionality to a ProductList
component.
4. Steps to Use HOC:
Key Takeaways:
● HOCs were widely used before React Hooks for sharing logic.
● They are still relevant for understanding how some libraries (e.g., Redux) work.
● Use HOCs to extend functionality when direct modification isn’t possible (e.g., third-party
components).
○ A pattern to create related components that work together for a specific task.
○ Example: A counter, modal windows, pagination, or tables.
2. Structure:
Benefits
Steps to Implement
○ Add child components as properties of the parent component for cleaner exports.
Example:
Counter.Label = Label;
Counter.Increase = IncreaseButton;
Counter.Decrease = DecreaseButton;
○
Example: Counter
// Parent Component
return (
<span>{children}</span>
</CounterContext.Provider>
);
};
// Child Components
return <span>{count}</span>;
};
const Increase = ({ icon }) => {
};
};
Counter.Count = Count;
Counter.Increase = Increase;
Counter.Decrease = Decrease;
// Usage Example
<Counter>
<Counter.Label>My Counter</Counter.Label>
0—------------------------The ENd—-----------------