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

React_Notes_Basic_to_Advanced_With_Examples

This document provides comprehensive notes on React.js, covering topics from basic concepts like components and JSX to advanced topics such as Redux and server-side rendering. It includes code examples for setting up React, managing state and props, handling events, and using hooks. Additionally, it discusses performance optimization techniques and integration with APIs.

Uploaded by

tiwari6973
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 views6 pages

React_Notes_Basic_to_Advanced_With_Examples

This document provides comprehensive notes on React.js, covering topics from basic concepts like components and JSX to advanced topics such as Redux and server-side rendering. It includes code examples for setting up React, managing state and props, handling events, and using hooks. Additionally, it discusses performance optimization techniques and integration with APIs.

Uploaded by

tiwari6973
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/ 6

React.

js Notes (Basic to Advanced) with Examples

1. Introduction to React
React is an open-source JavaScript library developed by Facebook for building user interfaces,
especially for single-page applications. Features include component-based architecture, virtual
DOM, and reusable components.
// Basic React Component
function Welcome() {
return <h1>Hello, React!</h1>;
}
export default Welcome;

2. Setting Up React
Two methods: Create React App (CRA) and Vite (fast bundler).
# Create React App
npx create-react-app my-app
cd my-app
npm start

# Vite Setup
npm create vite@latest my-app
cd my-app
npm install
npm run dev

3. JSX (JavaScript XML)


JSX allows writing HTML inside JavaScript. Must return a single parent element. Use className
instead of class.
const element = <h1>Welcome, {userName}!</h1>;

4. Components
Independent, reusable UI blocks. Types: Functional Components and Class Components.
// Functional Component
function Greeting(props) {
return <h1>Hello, {props.name}</h1>;
}

// Class Component
class GreetingClass extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
5. Props
Props are read-only inputs passed to components.
function User(props) {
return <p>Name: {props.name}, Age: {props.age}</p>;
}
<User name="Ankit" age={22} />

6. State
State is a mutable object that stores dynamic data inside a component. Managed using useState
hook in functional components.
import { useState } from 'react';

function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}

7. Event Handling
Handle user actions like click, input, and submit using event handlers.
function ButtonClick() {
function handleClick() {
alert("Button Clicked!");
}
return <button onClick={handleClick}>Click Me</button>;
}

8. Conditional Rendering
Show components based on conditions using if-else or ternary operator.
function UserStatus({ isLoggedIn }) {
return (
<div>
{isLoggedIn ? <h1>Welcome Back!</h1> : <h1>Please Login</h1>}
</div>
);
}

9. Lists and Keys


Render multiple elements using map(). Keys help React identify elements uniquely.
const users = ["Ankit", "Deepak", "Ravi"];
const list = users.map((user, index) => <li key={index}>{user}</li>);
10. Forms in React
Controlled components where input values are managed using state.
function Form() {
const [name, setName] = useState("");
return (
<form>
<input type="text" value={name} onChange={(e) => setName(e.target.value)} />
<p>Entered: {name}</p>
</form>
);
}

11. React Hooks


Functions that let you use state and lifecycle in functional components. Common hooks: useState,
useEffect, useContext, useReducer, useRef.
import { useEffect, useState } from "react";

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

useEffect(() => {
document.title = `Clicked ${count} times`;
}, [count]);

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


}

12. Lifecycle Methods


Class component lifecycle: Mounting (componentDidMount), Updating (componentDidUpdate),
Unmounting (componentWillUnmount).
class MyComponent extends React.Component {
componentDidMount() {
console.log("Mounted!");
}
componentDidUpdate() {
console.log("Updated!");
}
componentWillUnmount() {
console.log("Unmounted!");
}
render() {
return <h1>Lifecycle Example</h1>;
}
}

13. Context API


Helps to avoid props drilling by providing global state management.
const UserContext = React.createContext();
function App() {
return (
<UserContext.Provider value="Ankit">
<Profile />
</UserContext.Provider>
);
}

function Profile() {
const user = React.useContext(UserContext);
return <h1>User: {user}</h1>;
}

14. React Router


Used for navigation in single-page applications. Components: BrowserRouter, Routes, Route, Link.
import { BrowserRouter, Routes, Route, Link } from "react-router-dom";

function App() {
return (
<BrowserRouter>
<nav>
<Link to="/">Home</Link> | <Link to="/about">About</Link>
</nav>
<Routes>
<Route path="/" element={<h1>Home Page</h1>} />
<Route path="/about" element={<h1>About Page</h1>} />
</Routes>
</BrowserRouter>
);
}

15. Higher Order Components (HOC)


Functions that take a component and return a new component with extended functionality.
function withLogger(WrappedComponent) {
return function(props) {
console.log("Props:", props);
return <WrappedComponent {...props} />;
};
}

16. Error Boundaries


Catch errors in component tree and display fallback UI instead of breaking the app.
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError() {
return { hasError: true };
}
render() {
if (this.state.hasError) return <h1>Something went wrong.</h1>;
return this.props.children;
}
}

17. React Performance Optimization


Use memoization (React.memo, useMemo, useCallback), lazy loading (React.lazy, Suspense).
import React, { memo } from 'react';

const Child = memo(function({ value }) {


console.log("Rendered");
return <p>{value}</p>;
});

18. Redux
State management library with Store, Reducers, Actions, and Dispatch.
const increment = () => ({ type: "INCREMENT" });

function counterReducer(state = 0, action) {


if (action.type === "INCREMENT") return state + 1;
return state;
}

19. React with APIs


Fetch and render external data using Fetch API or Axios inside useEffect hook.
import { useEffect, useState } from "react";

function Users() {
const [users, setUsers] = useState([]);

useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/users")
.then(res => res.json())
.then(data => setUsers(data));
}, []);

return <ul>{users.map(user => <li key={user.id}>{user.name}</li>)}</ul>;


}

20. Advanced Topics


Includes Server-Side Rendering (Next.js), Static Site Generation, TypeScript with React, Custom
Hooks, and Testing (Jest).
// Example: Custom Hook
import { useState, useEffect } from "react";

function useWindowWidth() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
const handleResize = () => setWidth(window.innerWidth);
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, []);

return width;
}

You might also like