Creating and Running React App
npx create-react-app@5 my-app
dir my-app
npm start
- Destructuring allows us to extract values from arrays or properties from objects and assign them to variables.
- Example :
const book = getBook(3); const { title, author, pages, publicationDate, genres, hasMovieAdaptation } = book; console.log(author, title, genres);
- Extract elements from an array.
- Example:
const [primaryGenre, secondaryGenre, ...otherGenres] = genres; console.log(primaryGenre, secondaryGenre, otherGenres);
- The spread operator (
...
) allows us to spread elements of an array or object properties. - Example:
(Here, ...genres spreads out the genres array, and { ...book } spreads out the book object properties.)
const newGenres = ["epic fantasy", ...genres]; const updatedBook = { ...book, moviePublicationDate: "2001-12-19", pages: 1210, };
- Template literals provide an easy way to create strings. They allow embedded expressions, which can be multi-line.
- Example:
const summary = `${title}, a ${pages}-page long book, was written by ${author} and published in ${getYear(publicationDate)}.`; console.log(summary);
- The ternary operator is a shorthand for an
if-else
statement. - Example:
(This checks if pages is greater than 1000, then assigns the appropriate string.)
const pagesRange = pages > 1000 ? "over a thousand" : "less than 1000"; console.log(`The book has ${pagesRange} pages`);
- Logical AND (
&&
) and OR (||
) operators can be used for short-circuit evaluation. - Example:
console.log(hasMovieAdaptation && "This book has a movie"); const spanishTranslation = book.translations.spanish || "NOT TRANSLATED";
- Provides a default value when dealing with
null
orundefined
. - Example:
const count = book.reviews.librarything.reviewsCount ?? "no data"; console.log(count);
- Allows us to safely access deeply nested properties.
- Example:
function getTotalReviewCount(book) { const goodreads = book.reviews?.goodreads?.reviewsCount; const librarything = book.reviews?.librarything?.reviewsCount ?? 0; return goodreads + librarything; }
-
map()
: Transforms elements of an array. -
Example:
const titles = books.map((book) => book.title);
(Array ke har element pe operation perform karke naya array create karta hai)
-
filter()
: Filters elements of an array based on a condition. -
Example:
const longBooksWithMovie = books.filter((book) => book.pages > 500 && book.hasMovieAdaptation);
(Array ke elements ko condition ke basis pe filter karta hai)
-
reduce()
: Reduces the array to a single value. -
Example:
const pagesAllBooks = books.reduce((sum, book) => sum + book.pages, 0);
(Array ke elements ko ek single value mein reduce karta hai, jaise sum calculate karna.)
-
sort()
: Sorts elements of an array. -
Example:
const sortedByPages = books.slice().sort((a, b) => a.pages - b.pages);
(Array ko sort karta hai, jaise yaha books ko pages ke basis pe ascending order me sort kiya)
-
Adding:
const newBook = { id: 6, title: "Harry Potter and the Chamber of Secrets", author: "J. K. Rowling" }; const booksAfterAdd = [...books, newBook];
-
Deleting:
const booksAfterDelete = booksAfterAdd.filter((book) => book.id !== 3);
-
Updating:
const booksAfterUpdate = booksAfterDelete.map((book) => book.id === 1 ? { ...book, pages: 1210 } : book );
- Promises are used for asynchronous operations.
- Example:
(
fetch("https://jsonplaceholder.typicode.com/todos") .then((res) => res.json()) .then((data) => console.log(data));
fetch
returns a promise, and.then()
handles the resolved value.)
Async/Await
provides a way to work with asynchronous code in a synchronous manner.- Example:
(
async function getTodos() { const res = await fetch("https://jsonplaceholder.typicode.com/todos"); const data = await res.json(); console.log(data); return data; } const todos = getTodos(); console.log(todos);
await
pauses the execution until the promise resolves.)
- In React v18, we use
ReactDOM.createRoot
to render the root component:const root = ReactDOM.createRoot(document.getElementById("root")); root.render( <React.StrictMode> <App /> </React.StrictMode> );
- React applications are made of components.
- Components are the building blocks of user interfaces in React.
- Each component handles its own data, logic, and appearance.
- Components can be reused and nested within each other.
- Components are reusable pieces of UI.
- Example of a component:
function Header() { return <h1>Fast React Pizza Co.</h1>; }
- Break down the UI into smaller components.
- Example of creating a
Menu
component:function Menu() { return ( <main> <h2>Our Menu</h2> </main> ); }
- JSX (JavaScript XML) is a syntax extension of JavaScript that looks similar to HTML.
- It allows us to write HTML elements in JavaScript and place them in the DOM.
- Each JSX element is converted to a
React.createElement
function call.
Syntax:
const element = <h1>JavaScript XML</h1>;
- We can use JavaScript expressions inside JSX using
{}
. - Example:
const isOpen = true; return <div>{isOpen ? "Open" : "Closed"}</div>;
- React combines HTML, CSS, and JavaScript into components.
- Each component manages its own data, appearance, and logic.
- Inline styles are written as objects:
const style = { color: "red", fontSize: "48px" };
- Props are used to pass data from parent components to child components.
- Example:
function Pizza({ pizzaObj }) { console.log(pizzaObj); // if (pizzaObj.soldOut) return null; return ( <li className={`pizza ${pizzaObj.soldOut ? "sold-out" : ""}`}> <img src={pizzaObj.photoName} alt={pizzaObj.name} /> <div> <h3>{pizzaObj.name}</h3> <p>{pizzaObj.ingredients}</p> {/* {pizzaObj.soldOut ? ( <span>SOLD OUT</span> ) : ( <span>{pizzaObj.price}</span> )} */}
- Props are read-only and cannot be modified by the child component.
- This ensures one-way data flow, making the application predictable and easier to debug.
className
instead of HTMLβsclass
htmlFor
instead of HTMLβsfor
- Every tag needs to be closed.
- Event handlers and properties need to be camelCased.
- Use the
.map()
method to render lists of components. - Example:
<ul className="pizzas"> {pizzas.map((pizza) => ( <Pizza pizzaObj={pizza} key={pizza.name} /> ))} </ul>
- Render components conditionally using
&&
. - Example:
return <div>{isOpen && <p>We are open!</p>}</div>;
- Use the ternary operator for conditional rendering.
- Example:
return <div>{isOpen ? <p>We are open!</p> : <p>We are closed.</p>}</div>;
- Use multiple return statements to conditionally render components.
- Example:
if (!isOpen) return <p>We are closed.</p>; return <p>We are open!</p>;
- Extract repeated JSX into a new component for reusability.
- Example:
function PizzaList({ pizzas }) { return ( <ul> {pizzas.map(pizza => ( <Pizza key={pizza.name} pizzaObj={pizza} /> ))} </ul> ); }
- Destructure props for cleaner code.
- (Props ko directly function parameter me destructure karte hai, taaki code clean rahe)
- Example:
function Pizza({ pizzaObj: { name, ingredients, price, photoName, soldOut } }) { return <h3>{name}</h3>; }
- Use
<React.Fragment>
or<>
to group multiple elements without adding extra nodes to the DOM. - Multiple elements ko group karne ka tareeka without extra nodes in DOM.
- Example:
<React.Fragment>
<Header />
<Menu />
</React.Fragment>
- Set classes conditionally using template literals.
- Example:
<li className={`pizza ${soldOut ? "sold-out" : ""}`}></li>
-
Steps component manage karte hai navigation through different steps using state variables.
step
: Tracks the current step- (track karta hai ki user kaun se step pe hai, starting from 1)
isOpen
: Tracks if the steps section is open or closed- (control karta hai ki steps UI mein dikh rahe hain ya nahi, basically open ya close state ko handle karta hai)
function Steps() { const [step, setStep] = useState(1); const [isOpen, setIsOpen] = useState(true);
-
Event Handlers :
handlePrevious
: Decreases step by 1 if not already at the first step- ( user "Previous" button press karta hai to call hota hai, aur ye check karta hai ki agar current step 1 se zyada hai to ek step kam kar do)
handleNext
: Increases step by 1 if not already at the last step- (user "Next" button press karta hai to call hota hai, aur ye check karta hai ki agar current step 3 se kam hai to ek step badha do.)
function handlePrevious() { if (step > 1) setStep((s) => s - 1); } function handleNext() { if (step < 3) setStep((s) => s + 1); }
Current Step: 1 Current Step: 2 Current Step: 3 User presses "Next" User presses "Next" User presses "Next" handleNext
check:if (step < 3)
(1 < 3, true)handleNext
check:if (step < 3)
(2 < 3, true)handleNext
check:if (step < 3)
(3 < 3, false)Step becomes 2 Step becomes 3 Step remains 3 Current Step: 3 Current Step: 2 Current Step: 1 User presses "Previous" User presses "Previous" User presses "Previous" handlePrevious
check:if (step > 1)
(3 > 1, true)handlePrevious
check:if (step > 1)
(2 > 1, true)handlePrevious
check:if (step > 1)
(1 > 1, false)Step becomes 2 Step becomes 1 Step remains 1
- Events are bound using JSX syntax.
- Example: Handling a button click to toggle
isOpen
state.<button className="close" onClick={() => setIsOpen((is) => !is)}> × </button>
- Data that a component holds over time, necessary for information it needs to remember throughout the appβs lifecycle. Updating state triggers a re-render of the component.
- Example Usage:
const [step, setStep] = useState(1);
useState
hook se functional components me state add kar sakte hai- Syntax:
const [stateVariable, setStateFunction] = useState(initialValue);
- Example:
const [step, setStep] = useState(1);
- Directly modifying state variables.
// Incorrect test.name = "Fred"; setTest({ name: "Fred" });
- Using state functions.
State ko hamesha state function (like
// Correct setStep((s) => s + 1);
setStep
) se update kare
- Use multiple
useState
hooks for managing different pieces of state. - Example:
const [isOpen, setIsOpen] = useState(true);
return (
<div>
<button className="close" onClick={() => setIsOpen((is) => !is)}>
×
</button>
- Close Button:
- Yeh button steps section ko toggle karta hai (open/close).
onClick
event handler use karkesetIsOpen
function call kiya gaya hai joisOpen
state ko true/false karta hai.
{isOpen && (
<div className="steps">
- Conditional Rendering :
- Agar
isOpen
true hai toh steps section render hoga, warna nahi.
- Agar
<div className="numbers">
<div className={step >= 1 ? "active" : ""}>1</div>
<div className={step >= 2 ? "active" : ""}>2</div>
<div className={step >= 3 ? "active" : ""}>3</div>
</div>
step
value ke hisaab se "active" class conditionally apply hoti hai, jo current step ko highlight karti hai.
<StepMessage step={step}>
{messages[step - 1]}
<div className="buttons">
<Button
bgColor="#e7e7e7"
textColor="#333"
onClick={() => alert(`Learn how to ${messages[step - 1]}`)}
>
Learn how
</Button>
</div>
</StepMessage>
StepMessage
component current step ka message aur ek button display karta hai.messages
array mein step-wise messages hain.messages[step - 1]
se current step ka message milta hai.- "Learn how" button click karne se ek alert trigger hota hai jo current step ka message show karta hai.
Project |
---|
https://github.com/ravikant-diwakar/The-Far-Away-Travel-List |
- State (
useState
) is used within components to manage local data. - Props are used to pass data and functions between components.
Stateless/Presentational Components:
- No state management, only present data.
- Examples: Logo, NumResults.
Stateful Components:
- Manage their own state.
- Examples: Search, MovieDetails.
Structural Components:
- Provide the structure or layout of the app.
- Examples: App, NavBar.
Technique :
- Use children to directly pass components where needed.
Example:
function NavBar({ children }) {
return <nav className="nav-bar">{children}</nav>;
}
Define Props :
maxRating
,color
,size
,onSetRating
Example :
function StarRating({ maxRating = 5, color = "#fcc419", size = 48, onSetRating }) {
// Component logic
}
Framework | Library |
---|---|
- All-in-one solution with pre-included tools. | - Freedom to choose the best tools. |
- Complete structure for large-scale applications. | - Pieces of code shared for specific tasks. |
- Includes routing, styling, HTTP management, etc. | - React is a view library, focuses on UI rendering. |
- Batteries included, but less flexible. | - Needs external libraries for routing, styling, etc. |
- Example: Angular, Vue, Svelte. | - More flexibility, tailor-made solutions. |
- Example: React. |
- Large third-party library ecosystem.
- Popular libraries: React Router, React Query, Redux, Styled Components, Tailwind.
useState
adds state to functional components.
It returns the current state and a function to update it.
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
// more code
}
Here, count
starts at 0
, and setCount
updates it.
useEffect
handles side effects like data fetching or updating the DOM.
It runs after every render, but you can control when it runs by passing dependencies.
import React, { useState, useEffect } from 'react';
function TitleUpdater() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`; // Fixed the template string
}, [count]);
// more code
}
This updates the document title whenever count
changes.
useContext
accesses global data or shared state directly, without the need for prop drilling.
import React, { useContext } from 'react';
const MyContext = React.createContext();
function DisplayValue() {
const value = useContext(MyContext);
return <div>{value}</div>;
}
function App() {
return (
<MyContext.Provider value="Hello, World!">
<DisplayValue />
</MyContext.Provider>
);
}
useContext
retrieves the value provided by MyContext
and displays it.
useReducer
is used for managing complex state logic. It returns the current state and a dispatch function.
import React, { useReducer } from 'react';
const initialState = { count: 0 };
function reducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
default:
return state;
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState); // Fixed destructuring
return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>Increment</button>
</div>
);
}
useRef
allows you to access DOM elements or persist values across renders without causing a re-render.
import React, { useRef } from 'react';
function FocusInput() {
const inputRef = useRef(null);
const focusInput = () => {
inputRef.current.focus();
};
return (
<div>
<input ref={inputRef} type="text" />
<button onClick={focusInput}>Focus the input</button>
</div>
);
}
You can use this reference to directly interact with an input element.
useMemo
optimizes performance by memoizing a calculation, ensuring it only recalculates when dependencies change.
import React, { useMemo } from 'react';
function ExpensiveCalculation({ a, b }) {
const computeExpensiveValue = (a, b) => {
// Assume some expensive computation here
return a + b; // Simplified example
};
const memoizedValue = useMemo(() => {
return computeExpensiveValue(a, b);
}, [a, b]);
return <div>{memoizedValue}</div>;
}
This caches the result and only recalculates when a
or b
changes.
useCallback
memoizes functions, preventing them from being recreated unnecessarily.
import React, { useCallback } from 'react';
function CallBackApp({ a, b }) {
const memoizedCallback = useCallback(() => {
doSomething(a, b);
}, [a, b]);
return (
<div>
<button onClick={memoizedCallback}>Call Callback</button>
</div>
);
}
This ensures doSomething
only changes when a
or b
changes.
useCallback
differs from useMemo
in that useMemo
memoizes the result of a computation, while useCallback
memoizes the function itself.
This setup helps handle state transitions in a structured way.