React
React
🟡 2. Intermediate React
✅ Summary Checklist
• Learn core React concepts (JSX, Components, Props, State, Events)
• Master React Hooks
• Understand Routing and Context
• Build forms and manage global state
• Dive into advanced patterns and performance
• Learn TypeScript integration
• Test and deploy React apps
• Explore React frameworks (Next.js, Remix)
Resources:
https://www.youtube.com/watch?v=bMknfKXIFA8
Resources:
• Custom Hooks
• useRef, Forward Refs
• Code Splitting (React.lazy, Suspense)
• Error Boundaries
• Performance Optimization (React.memo, useMemo, useCallback)
• Portals
• Higher Order Components (HOC) and Render Props
Resources:
https://www.youtube.com/watch?v=6ThXsUwLWvc
Resources:
https://www.youtube.com/watch?v=JKOwJUM4_RM
https://www.youtube.com/watch?v=9zySeP5vH9c
https://www.youtube.com/watch?v=Z5iWr6Srsj8
• Netlify
• Vercel
• GitHub Pages
Resources:
https://www.youtube.com/watch?v=nhBVL41-_Cw
What is React?
• React is a JavaScript library for building user interfaces (mainly for web apps).
• Developed by Facebook in 2013.
• Component-based: UI is broken into small reusable components.
• Declarative: You describe what the UI should look like, React updates the DOM efficiently.
• SPA = Website that loads only one HTML page initially and dynamically updates the page without
reloading.
• Navigation feels instant (no full reloads).
• Example: Gmail, Facebook.
📚 2. Setting up React
Installing Node.js and npm
npm start
cd my-vite-app
npm install
npm run dev
my-app/
├── public/ // Static files (index.html)
Embedding expressions
JSX Attributes
<>
<h1>Title</h1>
<p>Description</p>
</>
📚 4. Components
What are Components?
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
Passing Props
📚 5. Props
What are Props?
function Child(props) {
return <h1>Hello {props.name}</h1>;
}
function Parent() {
return <Child name="Charlie" />;
}
Default Props
Child.defaultProps = {
name: "Guest"
};
Child.propTypes = {
name: PropTypes.string.isRequired
};
📚 6. State
What is State?
Using useState
function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Count {count}
</button>
);
}
Props vs State
Props State
Passed from parent Local to component
Immutable Mutable
Read-only Read/write
📚 7. Event Handling
Handling User Events
function Button() {
function handleClick() {
alert("Button clicked!");
}
return <button onClick={handleClick}>Click me</button>;
}
Synthetic Events
• React wraps browser events inside a SyntheticEvent for better cross-browser compatibility.
📚 8. Conditional Rendering
if inside JSX
if (isLoggedIn) {
return <Dashboard />;
} else {
return <Login />;
}
Ternary Operator
Short-circuit Evaluation
function NameList() {
return (
<ul>
{names.map(name => <li key={name}>{name}</li>)}
</ul>
);
}
Importance of Keys
const style = {
color: 'blue',
fontSize: '20px'
};
function Header() {
return <h1 style={style}>Hello!</h1>;
}
CSS Stylesheets
import './App.css';
CSS Modules
<h1 className={styles.header}>Hello</h1>
🚀 Conclusion
These are the most important fundamentals of React you must master first.
Without understanding this, you can't move effectively into hooks, advanced state management, or
frameworks like Next.js.
Rules of Hooks:
• Hooks must be called at the top level (not inside loops, conditions).
• Hooks must be called inside a React function component or a custom Hook.
useState (for Local State)
function Counter() {
const [count, setCount] = useState(0);
return (
<>
<h1>{count}</h1>
<button onClick={() => setCount(count + 1)}>Increment</button>
</>
);
}
function Timer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const interval = setInterval(() => setSeconds(s => s + 1), 1000);
function Profile() {
const user = useContext(UserContext);
Basic Structure
useEffect(() => {
// Code that runs after the component renders
}, [dependencies]);
function Users() {
const [users, setUsers] = useState([]);
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/users')
.then(res => res.json())
.then(data => setUsers(data));
}, []); // empty array = run once after initial render
return (
<ul>
{users.map(user => <li key={user.id}>{user.name}</li>)}
</ul>
);
}
Dependency Array
Cleanup Functions
useEffect(() => {
const timer = setInterval(() => console.log('Tick'), 1000);
📚 3. Forms Handling
React uses controlled components for form inputs.
Controlled Inputs
function LoginForm() {
const [email, setEmail] = useState('');
return (
<form>
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
<button type="submit">Submit</button>
</form>
);
}
Form Submission
function LoginForm() {
const [email, setEmail] = useState('');
return (
<form onSubmit={handleSubmit}>
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
<button type="submit">Submit</button>
</form>
);
}
function App() {
return (
<ThemeContext.Provider value="dark">
<Toolbar />
</ThemeContext.Provider>
);
}
function Toolbar() {
const theme = useContext(ThemeContext);
📚 5. React Router
Install React Router:
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="about" element={<About />} />
</Routes>
</BrowserRouter>
);
}
Navigation
<Link to="/">Home</Link>
<Link to="/about">About</Link>
Inside UserDetail:
function UserDetail() {
const { id } = useParams();
return <h1>User ID: {id}</h1>;
}
📚 6. Component Communication
Communicating Parent ➔ Child and Child ➔ Parent.
function Parent() {
return <Child message="Hello from Parent" />;
}
function Parent() {
const receiveMessage = (msg) => {
alert(msg);
};
📚 7. Lifting State Up
When siblings need to share state → move the state up to their common parent.
Example
Parent Component:
function Parent() {
const [count, setCount] = useState(0);
return (
<>
<Child1 count={count} />
<Child2 setCount={setCount} />
</>
);
}
Child1:
Child2:
🎯 Quick Summary:
Concept Purpose
useState Manage component local state
useEffect Handle side effects (like API calls)
useContext Global state access without props drilling
React Router Navigate between pages
Component Communication Pass data between components
Lifting State Up Share state between sibling components
📚 1. Composition vs Inheritance in React
⚡ What is Composition?
In simple words:
Example of Composition
<div className="card">
<h2>{title}</h2>
<p>{content}</p>
</div>
);
}
function App() {
return (
<Card title="React" content="Learning React Composition!" />
);
function WelcomeDialog() {
return (
<FancyBorder>
<h1>Welcome</h1>
<p>Thank you for visiting!</p>
</FancyBorder>
);
}
⚡ What is Inheritance?
Example in JavaScript:
class Animal {
speak() {
console.log('Animal speaks');
}
}
In React, you could technically extend components, but React team recommends NOT doing that.
📚 2. Why React uses Composition over Inheritance
Reasons:
Reason Explanation
Composition can combine multiple components easily without deep
Flexibility
hierarchies.
Simpler Code Components stay smaller and reusable, no complicated "is-a" relationships.
Better Separation of
Each component handles its own task (instead of big inheritance trees).
Concerns
Adding, updating, or removing functionality is much easier with
Easier Maintenance
composition.
React's philosophy:
“We believe that composition is a more natural solution than inheritance for sharing behavior between
components.”
📚 3. Error Boundaries
• An Error Boundary is a special React component that catches JavaScript errors anywhere in its
child component tree, and displays a fallback UI instead of crashing the whole app.
• Only class components can be error boundaries (for now).
• They catch errors during rendering, lifecycle methods, and constructors of their child components.
Basic structure:
static getDerivedStateFromError(error) {
// Update state so the next render shows the fallback UI
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
// Log the error somewhere (like a server or console)
console.error("Error caught by ErrorBoundary:", error, errorInfo);
}
render() {
if (this.state.hasError) {
// Fallback UI
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
function App() {
return (
<ErrorBoundary>
<ProblematicComponent />
</ErrorBoundary>
);
}
function ProblematicComponent() {
throw new Error('Crash!');
return <div>This will never render</div>;
}
plaintext
CopyEdit
/src
/components
ErrorBoundary.js
ProblematicComponent.js
App.js
🚀 Want a Bonus?
I can also show you how to create a Reusable ErrorBoundary Component that takes a custom fallback
UI as a prop, making it even more flexible and production-ready!
• React Query (now called TanStack Query) is a library for data fetching, caching, and synchronizing
server state.
• It handles background updates, automatic retries, and pagination out of the box.
Think of it like a "better alternative" to Redux when you're managing server-side data.
function Users() {
const { data, error, isLoading } = useQuery({
queryKey: ['users'],
queryFn: () => fetch('https://jsonplaceholder.typicode.com/users').then(res => res.json())
});
return (
<ul>
{data.map(user => <li key={user.id}>{user.name}</li>)}
</ul>
);
}
⚡ Redux
// counterSlice.js
initialState: { value: 0 },
reducers: {
increment: state => { state.value += 1 },
decrement: state => { state.value -= 1 }
}
});
// store.js
import { configureStore } from '@reduxjs/toolkit';
import counterReducer from './counterSlice';
// Counter.jsx
import { useSelector, useDispatch } from 'react-redux';
import { increment, decrement } from './counterSlice';
function Counter() {
const count = useSelector(state => state.counter.value);
const dispatch = useDispatch();
return (
<>
<h1>{count}</h1>
⚡ Zustand
}));
function Counter() {
const { count, increment } = useStore();
⚡ Jotai / Recoil
📚 3. Advanced Patterns
⚡ Compound Components
function sum(a, b) {
return a + b;
}
test('adds 1 + 2', () => {
expect(sum(1, 2)).toBe(3);
});
⚡ Component Testing (React Testing Library)
⚡ Mocking APIs
type ButtonProps = {
label: string;
};
Typing hooks:
📚 6. Accessibility (a11y)
<button>Click</button>
<input type="text" aria-label="Username" />
ARIA Roles:
Keyboard navigation:
onKeyDown={handleKeyDown}
⚡ Key Concepts:
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/service-worker.js');
}
⚡ Handling JWT
localStorage.setItem('token', yourJWTToken);
// On protected route
const token = localStorage.getItem('token');
if (!token) redirectToLogin();
Use React Context or libraries like Auth0, Firebase for managing auth.
⚡ Socket.io Example
function Chat() {
useEffect(() => {
socket.on('message', (msg) => console.log(msg));
return () => socket.disconnect();
}, []);
⚡ Using Nx or Turborepo
Example tools:
• Nx.dev
• Turborepo
📚 11. Micro-Frontends
⚡ What is Micro-Frontend?
• Split a big frontend into smaller, independent apps that are built and deployed separately.
Techniques:
• Module Federation (Webpack 5)
• Single SPA (Framework for micro-frontends)
⚡ Using react-i18next
function App() {
const { t } = useTranslation();
return <h1>{t('welcome')}</h1>;
}
⚡ Platforms:
🚀 Bonus:
Would you also like me to give you a Roadmap or Mini-Projects list where you can apply all these concepts
practically?
• Framework built on top of React for building server-side rendered (SSR) and static websites.
• Created by Vercel.
• Great for SEO, fast performance, and scalable apps.
• It supports:
o SSR (Server-side rendering)
o SSG (Static Site Generation)
o API routes (backend inside frontend)
o File-based routing (pages system)
o Image Optimization
o Incremental Static Regeneration (ISR)
📦 Installation:
npx create-next-app@latest
🔥 Key Concepts:
⚡ Example Structure:
/pages
index.js --> Home page
about.js --> About page
/api
hello.js --> API route
/public
images/
// pages/index.js
export default function Home() {
return <h1>Welcome to Next.js!</h1>
}
// pages/api/hello.js
export default function handler(req, res) {
res.status(200).json({ message: 'Hello Next.js!' });
}
📌 What is Gatsby?
🔥 Key Concepts:
// src/pages/index.js
import React from 'react';
📌 What is Remix?
Think of it as Next.js but with more control and better nested routing.
📦 Installation:
npx create-remix@latest
🔥 Key Concepts:
⚡ Example Loader:
// routes/index.jsx
import { json } from '@remix-run/node';
import { useLoaderData } from '@remix-run/react';
📦 Installation:
🔥 Key Concepts:
⚡ Example App:
🧠 Quick Tip:
• Next.js = Most popular choice today for React Web apps.
• Gatsby = Best for blogs and static sites.
• Remix = Future of full control React apps (data & routing).
• React Native = Mobile app development.
⚔️ When to Choose Next.js vs Remix
Feature Next.js Remix
Growing fast (less community, but
Popularity Very popular (huge community)
strong tech)
Slightly deeper concepts (loaders,
Learning Curve Easy to get started
actions)
Supports client-side, server-side,
Data Fetching Loaders fetch before rendering (better UX)
static generation
Limited (pages system, but no true Built-in nested routes and layouts
Nested Routing
nested layouts) (better control)
Manual form handling (useEffect, Built-in Actions (server-side form
Forms Handling
fetch) handling)
No API routes (you connect to external
API Routes Easy to create (pages/api)
APIs or backend)
Excellent (server-side rendered
SEO Excellent (SSR by default)
pages)
Middleware & Edge Supported (Next.js middleware,
Also supported
Functions Vercel Edge)
Offline/Progressive Designed for progressive enhancement
Client-side heavy
Enhancement (no JS fallback)
Startups, SaaS products, large Complex apps needing fine-grained control,
Best Use
teams, fast MVPs form-heavy apps
🎯 Simple Rule:
• Features:
o Homepage with intro/about me
o Blog listing (Markdown-based or CMS like Contentful)
o Dynamic blog pages ([slug].js)
o Contact form (use serverless function)
o SEO optimized (next/head)
o Image Optimization (next/image)
• Features:
o Landing page with product features
o Blog (optional)
o GraphQL to fetch images/posts
o Animated sections (scroll reveal)
o PWA support (gatsby-plugin-offline)
• Features:
o Nested routing for product categories
o Load products with loader functions
o Cart functionality (use loader + action)
o Checkout form with server-side handling
o Error boundaries for better UX
🧩 Weather App
• Features:
o Fetch weather data using OpenWeatherMap API
o Search city
o Display temperature, humidity, forecast
o Nice UI with React Native Paper or NativeBase
o Loading spinners and error states
Bonus idea: Publish app using Expo Go (no App Store approval needed)!
🧠 Pro Tip
If you master one project per ecosystem, you'll feel super confident handling any React stack!
🌟 Final Motivation
"Learning React basics is good, but mastering the ecosystem makes you unstoppable."