React Interview Questions with Answers
Most Asked React Interview Questions for Frontend Developer Roles
Introduction
React is a powerful JavaScript library for building user interfaces, developed by Meta. It has revolutionized frontend development with its component-based architecture, virtual DOM for efficient rendering, and declarative approach to building UIs. Used by companies like Facebook, Instagram, Netflix, and Airbnb, React is one of the most in-demand skills in the tech industry. This comprehensive guide presents 100+ carefully curated React interview questions and answers, covering everything from the fundamentals to advanced patterns. You'll master components, props, state, hooks (useState, useEffect, useContext, useReducer, useMemo, useCallback), custom hooks, Context API, state management (Redux, Zustand), routing with React Router, forms, API integration, performance optimization, testing, and real-world React development patterns. Whether you're preparing for a frontend developer role, a full-stack position, or a React specialist job, this question bank will solidify your understanding and give you the confidence to ace your interview. Start practicing now and become a React expert.
Why React?
- Component-based architecture – reusable and maintainable UI components
- Virtual DOM – efficient updates and rendering for high performance
- Declarative – describe UI for each state, React handles updates
- Rich ecosystem – extensive libraries and tools (Redux, React Router, Next.js)
- Strong community and corporate backing – used by Meta, Netflix, Airbnb, and more
- Excellent developer experience – hot reloading, DevTools, and debugging
- High demand in the job market – one of the most popular frontend frameworks
Most Asked React Interview Questions
React is a JavaScript library for building user interfaces, developed by Meta. It uses a component-based architecture and a virtual DOM for efficient rendering.
- Component-based: Build encapsulated components
- Virtual DOM: Efficient updates and rendering
- Declarative: Describe UI for each state
- Unidirectional data flow: One-way data binding
- Hooks: State and lifecycle in functional components
// Hello World in React
function App() {
return <h1>Hello, World!</h1>;
}
export default App;Variables in React are declared using JavaScript's let, const, or var. State variables use useState.
- let: Mutable variable
- const: Constant variable
- useState: State variable that triggers re-renders
- Props: Immutable variables passed from parent
- Context: Global variables accessible throughout the app
// Variables in React (JSX)
function App() {
const x = 10;
const y = 3.14;
const name = "React";
const isActive = true;
return (
<div>
<p>{x}</p>
<p>{y}</p>
<p>{name}</p>
<p>{String(isActive)}</p>
</div>
);
}React uses JavaScript data types including primitives, objects, arrays, and special React types.
- Primitive: string, number, boolean, null, undefined
- Object: Plain objects, arrays, functions
- React specific: JSX elements, components
- Prop types: PropTypes for type checking
- Event types: SyntheticEvent, MouseEvent, ChangeEvent
// Data Types in React
function DataTypes() {
const a = 10; // number
const d = 3.14; // number
const f = "Hello React"; // string
const g = true; // boolean
const j = [1, "hello", 3.14]; // array
const k = [1, 2, 3, 4, 5]; // array
const l = { name: "React", version: 18 }; // object
const person = { name: "Alice", age: 25, city: "NYC" };
const m = null; // null
return (
<div>
<p>{typeof a}</p>
<p>{typeof d}</p>
<p>{typeof f}</p>
</div>
);
}Functions in React are defined using JavaScript function declarations or arrow functions, with hooks for state and effects.
- Arrow functions:
const add = (a, b) => a + b - Function declarations:
function add(a, b) { return a + b } - Component functions:
const App = () => { return <div />; } - Event handlers:
const handleClick = () => { } - Custom hooks:
const useCustomHook = () => { }
// Functions in React
// Function declaration
function add(a, b) {
return a + b;
}
// Arrow function
const subtract = (a, b) => a - b;
// Function with default parameters
const greet = (name = "Guest") => {
return `Hello, ${name}!`;
};
// Component function
function Welcome({ name }) {
return <h1>Hello, {name}!</h1>;
}
// Function with multiple parameters
function sum(...numbers) {
return numbers.reduce((acc, n) => acc + n, 0);
}
// Hook function
function useCounter(initial = 0) {
const [count, setCount] = useState(initial);
return { count, setCount };
}
// Usage in component
function App() {
const result = add(5, 3);
const { count, setCount } = useCounter(0);
return (
<div>
<p>{result}</p>
<p>{greet("Alice")}</p>
<Welcome name="React" />
<p>{sum(1, 2, 3, 4, 5)}</p>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}Arrays in React are JavaScript arrays used for storing lists of data, often rendered using map() to create JSX elements.
- Creation:
const numbers = [1, 2, 3, 4, 5] - State arrays:
const [items, setItems] = useState([]) - Rendering:
items.map(item => <li key={item.id}>{item.name}</li>) - Methods:
push,pop,filter,map,reduce - Immutability:
setItems([...items, newItem])
// Arrays in React
function ArrayExample() {
const arr = [1, 2, 3, 4, 5];
// Map - transform each element
const doubled = arr.map(x => x * 2);
console.log(doubled);
// Filter - select elements
const evens = arr.filter(x => x % 2 === 0);
console.log(evens);
// Reduce - aggregate
const sum = arr.reduce((acc, x) => acc + x, 0);
console.log(sum);
// Push and pop (using spread for immutability)
const withSix = [...arr, 6];
const withoutLast = arr.slice(0, -1);
// Array operations
const a = [1, 2, 3];
const b = [4, 5, 6];
const c = a.map((x, i) => x + b[i]);
// Rendering arrays
const items = ['Apple', 'Banana', 'Orange'];
return (
<ul>
{items.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
);
}React uses JavaScript collections like Arrays, Objects, Sets, and Maps for storing and managing data.
- Arrays: Ordered lists of items
- Objects: Key-value pairs for structured data
- Sets: Unique values collection
- Maps: Key-value pairs with any key type
- Immutable patterns: Spread operator, Object.assign
// Objects as Dictionaries in React
function DictionaryExample() {
const person = {
name: "Alice",
age: 25,
city: "NYC"
};
// Access values
console.log(person.name);
console.log(person["age"]);
// Add/update values (using spread for immutability)
const updatedPerson = {
...person,
country: "USA",
age: 26
};
// Get with default
const city = person.city || "Unknown";
// Keys and values
const keys = Object.keys(person);
const values = Object.values(person);
// Iterate over object
const entries = Object.entries(person);
// Delete key (using destructuring)
const { country, ...personWithoutCountry } = updatedPerson;
// Check if key exists
const hasName = 'name' in person;
return (
<div>
{entries.map(([key, value]) => (
<p key={key}>{key}: {value}</p>
))}
</div>
);
}Components are the building blocks of React applications. They can be functional or class-based and return JSX elements.
- Functional components:
const MyComponent = () => { return <div />; } - Class components:
class MyComponent extends React.Component - Props: Input data passed to components
- State: Internal data managed with hooks
- Lifecycle: useEffect for managing side effects
// Arrays as Tuples in React
function TupleExample() {
// Create tuple-like array
const t = [1, "hello", 3.14, true];
// Access elements
console.log(t[0]);
console.log(t[1]);
// Array unpacking
const [a, b, c] = [10, 20, 30];
// Function returning multiple values
const divide = (a, b) => [Math.floor(a / b), a % b];
const [quotient, remainder] = divide(10, 3);
// Array concatenation
const t1 = [1, 2, 3];
const t2 = [4, 5, 6];
const t3 = [...t1, ...t2];
return (
<div>
<p>First: {t[0]}</p>
<p>Quotient: {quotient}, Remainder: {remainder}</p>
</div>
);
}Prop validation ensures components receive the correct props types. It can be done using PropTypes or TypeScript.
- PropTypes: Runtime type checking
- TypeScript: Compile-time type checking
- Required props:
prop.isRequired - Default props:
Component.defaultProps = - Custom validators: Custom prop validation functions
// Control Flow in React
function ControlFlow({ age, items }) {
// If-else (using ternary for JSX)
const status = age >= 18 ? "Adult" : "Minor";
// For loop (using map for rendering)
const fruits = ["apple", "banana", "orange"];
// Conditional rendering
const renderStatus = () => {
if (age < 18) return <p>Minor</p>;
if (age < 65) return <p>Adult</p>;
return <p>Senior</p>;
};
// Using && for conditional rendering
const showMessage = true;
return (
<div>
{/* Ternary operator */}
<p>Status: {status}</p>
{/* Function call */}
{renderStatus()}
{/* && operator */}
{showMessage && <p>This is a message</p>}
{/* Map for iteration */}
<ul>
{fruits.map((fruit, index) => (
<li key={index}>{fruit}</li>
))}
</ul>
{/* Conditional rendering with switch */}
{(() => {
switch(age) {
case 0: return <p>Baby</p>;
case 18: return <p>Adult</p>;
default: return <p>Other</p>;
}
})()}
</div>
);
}React uses JavaScript's null and undefined handling with optional chaining and conditional rendering for safety.
- Optional chaining:
user?.name - Nullish coalescing:
value ?? 'default' - Conditional rendering:
{data && <div>{data}</div>} - Default values:
const name = user?.name || 'Guest' - TypeScript: Strict null checking
// Array Generation in React
function ArrayGeneration() {
// Using Array.from
const squares = Array.from({ length: 10 }, (_, i) => (i + 1) ** 2);
// Using map with range
const evens = Array.from({ length: 20 }, (_, i) => i + 1)
.filter(x => x % 2 === 0);
// Nested arrays
const matrix = Array.from({ length: 3 }, (_, i) =>
Array.from({ length: 3 }, (_, j) => [i + 1, j + 1])
);
// Conditional array
const results = Array.from({ length: 10 }, (_, i) => i + 1)
.map(x => x % 2 === 0 ? "even" : "odd");
// Rendering generated arrays
return (
<div>
<h3>Squares:</h3>
<ul>
{squares.map((num, i) => (
<li key={i}>{num}</li>
))}
</ul>
</div>
);
}Conditional rendering in React is done using if statements, ternary operators, logical AND (&&), or switch statements.
- If-else:
if (condition) { return <div />; } - Ternary:
{condition ? <div /> : <span />} - Logical AND:
{condition && <div />} - Switch:
switch (status) { case 'loading': ... } - Immediately invoked:
{(() => { if (condition) return <div />; })()}
// Strings in React
function StringExample() {
const str1 = "Hello";
const str2 = "World";
// String concatenation
const greeting = str1 + " " + str2;
// String interpolation (template literals)
const name = "React";
const version = 18;
const message = `Welcome to ${name} version ${version}`;
// String functions
const text = "Hello, World!";
const length = text.length;
const upper = text.toUpperCase();
const lower = text.toLowerCase();
const replaced = text.replace("World", "React");
// Substring
const sub = text.substring(0, 5);
// Split and join
const words = "Hello World React".split(" ");
const joined = words.join("-");
// String comparison
const isEqual = "hello" === "hello";
// String formatting
const formatted = `Value: ${3.14159.toFixed(2)}`;
return (
<div>
<p>{greeting}</p>
<p>{message}</p>
<p>{upper}</p>
<p>{joined}</p>
</div>
);
}Props (properties) are read-only inputs passed to components. They allow parent components to pass data to child components.
- Passing props:
<Component name="Alice" /> - Receiving props:
const Component = ({ name }) => {} - Default props:
Component.defaultProps = {} - Children:
props.children - Immutable: Props cannot be modified by child
// Modules in React
// App.jsx - Main component
import React, { useState, useEffect } from 'react';
import Header from './components/Header';
import Footer from './components/Footer';
import { useAuth } from './hooks/useAuth';
import './App.css';
// Named export
export const API_URL = 'https://api.example.com';
// Default export
export default function App() {
const { user, login } = useAuth();
return (
<div>
<Header />
<main>Content</main>
<Footer />
</div>
);
}
// components/Header.jsx
export function Header() {
return <header>Header</header>;
}
// components/Footer.jsx
export default function Footer() {
return <footer>Footer</footer>;
}
// hooks/useAuth.js
export function useAuth() {
const [user, setUser] = useState(null);
const login = (userData) => setUser(userData);
return { user, login };
}
// Using dynamic import
const LazyComponent = React.lazy(() => import('./LazyComponent'));
// Context module
export const AppContext = React.createContext();
// Usage of context
function AppProvider({ children }) {
const [theme, setTheme] = useState('light');
return (
<AppContext.Provider value={{ theme, setTheme }}>
{children}
</AppContext.Provider>
);
}State is internal data that can change over time and triggers re-renders when updated. It's managed using the useState hook.
- useState:
const [state, setState] = useState(initial) - Immutable updates:
setState({ ...state, newKey: value }) - Functional updates:
setState(prev => prev + 1) - Lazy initialization:
useState(() => expensiveComputation()) - State lifting: Moving state to parent component
// Components and Types in React
// Functional component with TypeScript
interface PersonProps {
name: string;
age: number;
city?: string;
}
const Person: React.FC<PersonProps> = ({ name, age, city = "Unknown" }) => {
return (
<div>
<p>Name: {name}</p>
<p>Age: {age}</p>
<p>City: {city}</p>
</div>
);
};
// Class component
class Animal extends React.Component {
constructor(props) {
super(props);
this.state = { name: props.name, age: props.age };
}
render() {
return (
<div>
<p>Name: {this.state.name}</p>
<p>Age: {this.state.age}</p>
</div>
);
}
}
// Component with children
function Card({ children, title }) {
return (
<div className="card">
<h3>{title}</h3>
{children}
</div>
);
}
// Higher-order component
function withLogger(WrappedComponent) {
return function WithLogger(props) {
useEffect(() => {
console.log('Component mounted');
return () => console.log('Component unmounted');
}, []);
return <WrappedComponent {...props} />;
};
}
// Usage
function App() {
return (
<div>
<Person name="Alice" age={25} city="NYC" />
<Animal name="Rex" age={3} />
<Card title="Welcome">
<p>This is card content</p>
</Card>
</div>
);
}Custom hooks are reusable functions that encapsulate stateful logic. They allow sharing logic between components.
- Naming: Must start with
use - Composition: Can use other hooks inside
- Reusable: Share logic across components
- Cleaner code: Extract complex logic from components
- Testing: Easier to test isolated logic
// Type System in React (TypeScript)
// Basic types
interface User {
id: number;
name: string;
email: string;
age?: number; // optional
}
// Union types
type Status = 'idle' | 'loading' | 'success' | 'error';
// Generic component
interface ListProps<T> {
items: T[];
renderItem: (item: T) => React.ReactNode;
}
function List<T>({ items, renderItem }: ListProps<T>) {
return <ul>{items.map((item, i) => <li key={i}>{renderItem(item)}</li>)}</ul>;
}
// Type assertions
function TypeExample() {
const value: unknown = "Hello";
const str = value as string;
const len = (value as string).length;
// Type checking
const isString = typeof value === 'string';
const isNumber = typeof value === 'number';
// Function with type guards
function isUser(obj: any): obj is User {
return obj && typeof obj.name === 'string' && typeof obj.email === 'string';
}
const data: unknown = { name: 'Alice', email: 'alice@example.com' };
if (isUser(data)) {
console.log(data.name);
}
return null;
}
// Type for props
type ButtonProps = {
variant: 'primary' | 'secondary';
size: 'sm' | 'md' | 'lg';
children: React.ReactNode;
onClick?: () => void;
};
const Button: React.FC<ButtonProps> = ({ variant, size, children, onClick }) => {
return (
<button className={`btn-${variant} btn-${size}`} onClick={onClick}>
{children}
</button>
);
};Error handling in React uses try-catch blocks, Error Boundaries, and error states to manage and display errors.
- Try-catch: Handle synchronous errors
- Async/await: Catch errors in async operations
- Error Boundaries: Catch component errors
- Error state:
const [error, setError] = useState(null) - Logging: Console.error for debugging
// Exception Handling in React
function ErrorExample() {
const [error, setError] = useState(null);
// Try-catch in event handlers
const handleClick = () => {
try {
// Code that might error
const result = 10 / 0;
console.log(result);
} catch (e) {
setError('Division by zero');
}
};
// Error boundary component
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false, error: null };
}
static getDerivedStateFromError(error) {
return { hasError: true, error };
}
componentDidCatch(error, errorInfo) {
console.log('Error:', error, errorInfo);
}
render() {
if (this.state.hasError) {
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
// Try-catch in async functions
const fetchData = async () => {
try {
const response = await fetch('https://api.example.com');
const data = await response.json();
return data;
} catch (error) {
console.error('Fetch error:', error);
throw error;
}
};
// Custom error hook
function useErrorHandler() {
const [error, setError] = useState(null);
const handleError = (err) => {
setError(err);
console.error(err);
};
return { error, handleError };
}
return (
<ErrorBoundary>
<div>
<button onClick={handleClick}>Click me</button>
{error && <p>Error: {error}</p>}
</div>
</ErrorBoundary>
);
}Arrow functions are a concise way to write functions in JavaScript. They are commonly used for event handlers and callbacks in React.
- Syntax:
const fn = () => { } - Lexical this: Inherits this from parent scope
- Implicit return:
const add = (a, b) => a + b - Event handlers:
onClick={() => handleClick()} - Higher-order:
const double = (x) => x * 2
// File I/O in React
function FileExample() {
const [fileContent, setFileContent] = useState('');
const [fileList, setFileList] = useState([]);
// Reading files
const handleFileRead = (event) => {
const file = event.target.files[0];
const reader = new FileReader();
reader.onload = (e) => {
setFileContent(e.target.result);
};
reader.readAsText(file);
};
// Reading as data URL (for images)
const handleImageRead = (event) => {
const file = event.target.files[0];
const reader = new FileReader();
reader.onload = (e) => {
const imageUrl = e.target.result;
// Use imageUrl for img src
};
reader.readAsDataURL(file);
};
// Reading multiple files
const handleMultipleFiles = (event) => {
const files = Array.from(event.target.files);
const readers = files.map(file => {
return new Promise((resolve) => {
const reader = new FileReader();
reader.onload = (e) => {
resolve({ name: file.name, content: e.target.result });
};
reader.readAsText(file);
});
});
Promise.all(readers).then(results => {
setFileList(results);
});
};
// Download file
const downloadFile = () => {
const content = 'Hello, World!';
const blob = new Blob([content], { type: 'text/plain' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'file.txt';
a.click();
URL.revokeObjectURL(url);
};
// File input
return (
<div>
<input type="file" onChange={handleFileRead} />
<input type="file" accept="image/*" onChange={handleImageRead} />
<input type="file" multiple onChange={handleMultipleFiles} />
<button onClick={downloadFile}>Download</button>
{fileContent && <pre>{fileContent}</pre>}
<ul>
{fileList.map((f, i) => (
<li key={i}>{f.name}</li>
))}
</ul>
</div>
);
}useEffect is a hook that handles side effects in functional components. It runs after render and can clean up on unmount.
- Basic:
useEffect(() => { }, []) - Dependencies: Controls when effect runs
- Cleanup: Return function for cleanup
- Data fetching: API calls and async operations
- Subscriptions: Event listeners, timers
// Packages in React
// Package.json dependencies
/*
{
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.8.0",
"axios": "^1.3.0",
"@mui/material": "^5.11.0",
"react-query": "^3.39.0",
"zustand": "^4.3.0",
"react-hook-form": "^7.42.0",
"react-helmet-async": "^1.3.0"
},
"devDependencies": {
"@types/react": "^18.0.0",
"@typescript-eslint/eslint-plugin": "^5.0.0",
"vite": "^4.0.0",
"vitest": "^0.28.0"
}
}
*/
// Installing packages
// npm install react-router-dom
// npm install axios
// npm install @mui/material @emotion/react @emotion/styled
// Using packages
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import axios from 'axios';
import { Button, TextField } from '@mui/material';
import { useQuery } from 'react-query';
import { useForm } from 'react-hook-form';
import { Helmet } from 'react-helmet-async';
// Vite config
/*
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [react()],
server: {
port: 3000,
},
});
*/
// Using environment variables
// .env
// VITE_API_URL=https://api.example.com
// const apiUrl = import.meta.env.VITE_API_URL;Custom hooks allow extracting and reusing stateful logic across components. They improve code organization and reusability.
- Encapsulation: Encapsulate complex logic
- Reuse: Share logic between components
- Cleaner code: Reduce component complexity
- Testing: Easier to unit test
- Composition: Combine multiple hooks
// Plotting in React
function PlotExample() {
// Using Recharts
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend } from 'recharts';
const data = [
{ name: 'Jan', value: 400 },
{ name: 'Feb', value: 300 },
{ name: 'Mar', value: 600 },
{ name: 'Apr', value: 800 },
{ name: 'May', value: 500 },
];
// Using Chart.js with react-chartjs-2
import { Chart as ChartJS, CategoryScale, LinearScale, PointElement, LineElement } from 'chart.js';
import { Line } from 'react-chartjs-2';
ChartJS.register(CategoryScale, LinearScale, PointElement, LineElement);
const chartData = {
labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
datasets: [
{
label: 'Sales',
data: [400, 300, 600, 800, 500],
borderColor: 'rgb(75, 192, 192)',
backgroundColor: 'rgba(75, 192, 192, 0.2)',
},
],
};
// Using D3 with React
import * as d3 from 'd3';
const [svgRef, setSvgRef] = useState(null);
useEffect(() => {
if (svgRef) {
const svg = d3.select(svgRef);
svg.selectAll('*').remove();
const margin = { top: 20, right: 20, bottom: 30, left: 40 };
const width = 400 - margin.left - margin.right;
const height = 300 - margin.top - margin.bottom;
const x = d3.scaleLinear()
.domain([0, 10])
.range([0, width]);
const y = d3.scaleLinear()
.domain([0, 100])
.range([height, 0]);
const line = d3.line()
.x((d, i) => x(i))
.y(d => y(d));
const g = svg.append('g')
.attr('transform', `translate(${margin.left},${margin.top})`);
g.append('path')
.datum([10, 20, 30, 40, 50, 60, 70, 80, 90, 100])
.attr('class', 'line')
.attr('d', line);
}
}, [svgRef]);
return (
<div>
{/* Recharts */}
<LineChart width={400} height={300} data={data}>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="name" />
<YAxis />
<Tooltip />
<Legend />
<Line type="monotone" dataKey="value" stroke="#8884d8" />
</LineChart>
{/* Chart.js */}
<Line data={chartData} />
{/* D3 */}
<svg ref={setSvgRef} width={400} height={300}></svg>
</div>
);
}TypeScript adds static typing to React, improving code quality and developer experience with type checking and IntelliSense.
- Type annotations:
const name: string = 'Alice' - Interfaces:
interface Props { name: string } - Generic components:
<T>(props: Props<T>) => {} - Type inference: Automatically infer types
- Strict mode:
"strict": truein tsconfig
// Data Structures in React
function DataStructuresExample() {
// Stack (using array)
const stack = [];
stack.push(1);
stack.push(2);
stack.push(3);
const popped = stack.pop();
// Queue (using array)
const queue = [];
queue.push(1);
queue.push(2);
queue.push(3);
const dequeued = queue.shift();
// Map (using object or Map)
const map = new Map();
map.set('Alice', 25);
map.set('Bob', 30);
map.set('Charlie', 35);
// Set (using Set)
const set = new Set([1, 2, 2, 3, 3, 4]);
// Use in state
const [items, setItems] = useState([1, 2, 3]);
const [mapData, setMapData] = useState(new Map());
const [setData, setSetData] = useState(new Set());
// Adding to stack (immutable)
const addToStack = (item) => {
setItems(prev => [...prev, item]);
};
// Pop from stack (immutable)
const popFromStack = () => {
setItems(prev => prev.slice(0, -1));
};
// Adding to Map (immutable)
const addToMap = (key, value) => {
setMapData(prev => new Map(prev).set(key, value));
};
// Adding to Set (immutable)
const addToSet = (value) => {
setSetData(prev => new Set(prev).add(value));
};
return (
<div>
<h3>Stack</h3>
<p>Items: {items.join(', ')}</p>
<button onClick={() => addToStack(items.length + 1)}>Push</button>
<button onClick={popFromStack}>Pop</button>
<h3>Map</h3>
{Array.from(mapData.entries()).map(([key, value]) => (
<p key={key}>{key}: {value}</p>
))}
<h3>Set</h3>
<p>{Array.from(setData).join(', ')}</p>
</div>
);
}Higher-Order Components (HOCs) are functions that take a component and return an enhanced component. They are used for cross-cutting concerns.
- Definition:
const withAuth = (Component) => (props) => { } - Enhancement: Add features to components
- Composition: Chain multiple HOCs
- Common uses: Authentication, logging, data fetching
- Alternative: Custom hooks (preferred approach)
// Statistics in React
function StatisticsExample() {
const [data, setData] = useState([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
// Mean
const mean = data.reduce((a, b) => a + b, 0) / data.length;
// Median
const sorted = [...data].sort((a, b) => a - b);
const mid = Math.floor(sorted.length / 2);
const median = sorted.length % 2 === 0
? (sorted[mid - 1] + sorted[mid]) / 2
: sorted[mid];
// Standard deviation
const variance = data.reduce((acc, x) => acc + (x - mean) ** 2, 0) / data.length;
const stdDev = Math.sqrt(variance);
// Correlation
const x = [1, 2, 3, 4, 5];
const y = [2, 4, 6, 8, 10];
const correlation = (x, y) => {
const n = x.length;
const sumX = x.reduce((a, b) => a + b, 0);
const sumY = y.reduce((a, b) => a + b, 0);
const sumXY = x.reduce((acc, xi, i) => acc + xi * y[i], 0);
const sumX2 = x.reduce((acc, xi) => acc + xi * xi, 0);
const sumY2 = y.reduce((acc, yi) => acc + yi * yi, 0);
return (n * sumXY - sumX * sumY) /
Math.sqrt((n * sumX2 - sumX * sumX) * (n * sumY2 - sumY * sumY));
};
// Quantiles
const quantile = (arr, q) => {
const sorted = [...arr].sort((a, b) => a - b);
const pos = (sorted.length - 1) * q;
const base = Math.floor(pos);
const frac = pos - base;
if (frac === 0) return sorted[base];
return sorted[base] + frac * (sorted[base + 1] - sorted[base]);
};
const q25 = quantile(data, 0.25);
const q75 = quantile(data, 0.75);
return (
<div>
<h3>Statistics</h3>
<p>Data: {data.join(', ')}</p>
<p>Mean: {mean.toFixed(2)}</p>
<p>Median: {median.toFixed(2)}</p>
<p>Std Dev: {stdDev.toFixed(2)}</p>
<p>Q25: {q25.toFixed(2)}, Q75: {q75.toFixed(2)}</p>
<p>Correlation: {correlation(x, y).toFixed(2)}</p>
</div>
);
}Higher-order functions are functions that operate on other functions. They can accept functions as arguments or return functions.
- Function arguments:
const operate = (a, b, fn) => fn(a, b) - Returning functions:
const getMultiplier = (x) => (y) => x * y - Composition: Combining functions
- Array methods:
map,filter,reduce - Debouncing:
debounce(() => { }, 300)
// Linear Algebra in React
function LinearAlgebraExample() {
// Matrix multiplication
const matMul = (A, B) => {
const rows = A.length;
const cols = B[0].length;
const inner = B.length;
const result = Array.from({ length: rows }, () => Array(cols).fill(0));
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
for (let k = 0; k < inner; k++) {
result[i][j] += A[i][k] * B[k][j];
}
}
}
return result;
};
// Transpose
const transpose = (matrix) => {
const rows = matrix.length;
const cols = matrix[0].length;
const result = Array.from({ length: cols }, () => Array(rows).fill(0));
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
result[j][i] = matrix[i][j];
}
}
return result;
};
// Determinant (for 2x2 and 3x3)
const determinant = (matrix) => {
const n = matrix.length;
if (n === 1) return matrix[0][0];
if (n === 2) return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0];
let det = 0;
for (let j = 0; j < n; j++) {
const subMatrix = matrix.slice(1).map(row =>
row.filter((_, k) => k !== j)
);
det += (j % 2 === 0 ? 1 : -1) * matrix[0][j] * determinant(subMatrix);
}
return det;
};
// Vector operations
const vectorAdd = (a, b) => a.map((x, i) => x + b[i]);
const vectorDot = (a, b) => a.reduce((acc, x, i) => acc + x * b[i], 0);
const vectorNorm = (a) => Math.sqrt(a.reduce((acc, x) => acc + x * x, 0));
const A = [[1, 2, 3], [4, 5, 6], [7, 8, 10]];
const B = [[1], [2], [3]];
const v1 = [1, 2, 3];
const v2 = [4, 5, 6];
const product = matMul(A, B);
const transposed = transpose(A);
const det = determinant(A);
const dot = vectorDot(v1, v2);
const norm = vectorNorm(v1);
return (
<div>
<h3>Linear Algebra</h3>
<p>Matrix product: {JSON.stringify(product)}</p>
<p>Transpose: {JSON.stringify(transposed)}</p>
<p>Determinant: {det}</p>
<p>Dot product: {dot}</p>
<p>Norm: {norm.toFixed(2)}</p>
</div>
);
}Async/await is used in React for handling asynchronous operations like API calls, database operations, and side effects.
- async functions:
const fetchData = async () => { } - await: Wait for promise resolution
- Error handling:
try { } catch (error) { } - Parallel requests:
await Promise.all([...]) - useEffect: Async inside useEffect
// Dates and Time in React
function DateExample() {
const [now, setNow] = useState(new Date());
// Date creation
const date1 = new Date(2024, 0, 1);
const date2 = new Date(2024, 0, 1, 12, 0, 0);
// Date arithmetic
const addDays = (date, days) => {
const result = new Date(date);
result.setDate(result.getDate() + days);
return result;
};
const addMonths = (date, months) => {
const result = new Date(date);
result.setMonth(result.getMonth() + months);
return result;
};
// Date difference
const diffDays = (date1, date2) => {
const diff = date2 - date1;
return Math.floor(diff / (1000 * 60 * 60 * 24));
};
// Formatting dates
const formatDate = (date) => {
return date.toISOString().split('T')[0];
};
const formatDateTime = (date) => {
return date.toISOString().replace('T', ' ').slice(0, 19);
};
// Date functions
const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, '0');
const day = String(now.getDate()).padStart(2, '0');
const dayOfWeek = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'][now.getDay()];
// Date range
const start = new Date(2024, 0, 1);
const end = new Date(2024, 0, 10);
const dateRange = [];
for (let d = new Date(start); d <= end; d.setDate(d.getDate() + 1)) {
dateRange.push(new Date(d));
}
// Using libraries
// npm install date-fns
import { format, differenceInDays, addDays as addDaysFns } from 'date-fns';
const formatted = format(now, 'yyyy-MM-dd HH:mm:ss');
return (
<div>
<h3>Dates</h3>
<p>Now: {formatDateTime(now)}</p>
<p>Date 1: {formatDate(date1)}</p>
<p>Date 2: {formatDateTime(date2)}</p>
<p>Date + 10 days: {formatDate(addDays(date1, 10))}</p>
<p>Date + 2 months: {formatDate(addMonths(date1, 2))}</p>
<p>Days difference: {diffDays(date1, date2)}</p>
<p>Year: {year}, Month: {month}, Day: {day}</p>
<p>Day of week: {dayOfWeek}</p>
<p>Date range: {dateRange.map(d => formatDate(d)).join(', ')}</p>
<p>Using date-fns: {formatted}</p>
</div>
);
}Custom hooks for async operations encapsulate fetching logic, loading states, error handling, and data management.
- useAsync: Handle async operations
- useFetch: Data fetching with state
- usePolling: Regular data updates
- usePagination: Paginated data loading
- useDebounce: Debounced async operations
// Regular Expressions in React
function RegexExample() {
const [text, setText] = useState('hello world');
const [matches, setMatches] = useState([]);
// Match
const matchRegex = () => {
const re = /hello/;
const result = text.match(re);
setMatches(result ? [result[0]] : []);
};
// Find all
const findAllMatches = () => {
const text2 = 'hello world hello again';
const matches = text2.match(/hello/g);
setMatches(matches || []);
};
// Regex with capture groups
const extractDate = () => {
const text3 = 'Date: 2024-01-01';
const pattern = /(\d{4})-(\d{2})-(\d{2})/;
const match = text3.match(pattern);
if (match) {
setMatches([`Year: ${match[1]}, Month: ${match[2]}, Day: ${match[3]}`]);
}
};
// Replace with regex
const replaceWithRegex = () => {
const replaced = 'Hello 123 World'.replace(/\d+/g, 'NUM');
setMatches([replaced]);
};
// Case insensitive
const caseInsensitive = () => {
const match = 'HELLO world'.match(/hello/i);
setMatches(match ? [match[0]] : []);
};
// Split with regex
const splitWithRegex = () => {
const parts = 'Hello World React'.split(/[\s,]+/);
setMatches(parts);
};
// Replace callback
const replaceCallback = () => {
const result = '1 2 3 4 5'.replace(/\d+/g, (match) => {
return String(parseInt(match) * 2);
});
setMatches([result]);
};
// Input validation
const validateEmail = (email) => {
const pattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return pattern.test(email);
};
const validatePhone = (phone) => {
const pattern = /^\d{3}-\d{4}$/;
return pattern.test(phone);
};
return (
<div>
<h3>Regular Expressions</h3>
<input
type="text"
value={text}
onChange={(e) => setText(e.target.value)}
placeholder="Enter text"
/>
<button onClick={matchRegex}>Match</button>
<button onClick={findAllMatches}>Find All</button>
<button onClick={extractDate}>Extract Date</button>
<button onClick={replaceWithRegex}>Replace</button>
<button onClick={caseInsensitive}>Case Insensitive</button>
<button onClick={splitWithRegex}>Split</button>
<button onClick={replaceCallback}>Replace Callback</button>
<ul>
{matches.map((m, i) => (
<li key={i}>{m}</li>
))}
</ul>
<p>Email valid: {String(validateEmail('test@example.com'))}</p>
<p>Phone valid: {String(validatePhone('123-4567'))}</p>
</div>
);
}Context API provides a way to pass data through the component tree without passing props manually at every level.
- createContext: Create a context
- Provider: Provide values to the tree
- Consumer: Access context values
- useContext: Hook for consuming context
- Custom providers: Create with hooks for state
// Parallel Computing in React
function ParallelExample() {
// Using Web Workers
const [result, setResult] = useState(null);
const runWorker = () => {
const worker = new Worker(new URL('./worker.js', import.meta.url));
worker.postMessage({ data: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] });
worker.onmessage = (e) => {
setResult(e.data);
worker.terminate();
};
};
// Worker code (worker.js)
/*
self.onmessage = function(e) {
const data = e.data.data;
const result = data.map(x => x * x);
self.postMessage(result);
};
*/
// Using WebAssembly
const runWasm = async () => {
// Load and run WebAssembly module
const response = await fetch('module.wasm');
const bytes = await response.arrayBuffer();
const wasm = await WebAssembly.instantiate(bytes, {});
const result = wasm.instance.exports.add(5, 3);
setResult(result);
};
// Using Service Workers for background sync
/*
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js');
navigator.serviceWorker.ready.then(registration => {
registration.sync.register('sync-data');
});
}
*/
// Using SharedArrayBuffer
const useSharedMemory = () => {
const buffer = new SharedArrayBuffer(1024);
const view = new Int32Array(buffer);
Atomics.store(view, 0, 42);
const value = Atomics.load(view, 0);
setResult(value);
};
// Using WebGPU for parallel computation
/*
if (navigator.gpu) {
const adapter = await navigator.gpu.requestAdapter();
const device = await adapter.requestDevice();
// Setup compute pipeline
}
*/
// Using requestIdleCallback for background tasks
const useIdleCallback = () => {
requestIdleCallback(() => {
// Perform background task
console.log('Background task executed');
});
};
// Using setTimeout for pseudo-parallelism
const runParallelTasks = async () => {
const tasks = [1, 2, 3, 4, 5].map((n) => {
return new Promise((resolve) => {
setTimeout(() => {
resolve(n * n);
}, 1000);
});
});
const results = await Promise.all(tasks);
setResult(results);
};
return (
<div>
<h3>Parallel Computing</h3>
<button onClick={runWorker}>Run Worker</button>
<button onClick={runWasm}>Run WASM</button>
<button onClick={useSharedMemory}>Shared Memory</button>
<button onClick={runParallelTasks}>Parallel Tasks</button>
{result && <p>Result: {JSON.stringify(result)}</p>}
</div>
);
}Redux-like state management can be implemented using useReducer hook and Context API for global state management.
- useReducer: Manage complex state
- Context: Provide state globally
- Actions: Define action types
- Reducers: Pure functions for state updates
- Custom hooks: Use context with custom hook
// Metaprogramming in React
function MetaprogrammingExample() {
// Dynamic component creation
const createComponent = (name, props) => {
const Component = (props) => {
return <div>{props.children}</div>;
};
Component.displayName = name;
return Component;
};
const DynamicComponent = createComponent('Dynamic');
// Higher-order component for logging
const withLogging = (WrappedComponent) => {
return function WithLogging(props) {
useEffect(() => {
console.log(`${WrappedComponent.name} mounted`);
return () => console.log(`${WrappedComponent.name} unmounted`);
}, []);
return <WrappedComponent {...props} />;
};
};
const LoggedComponent = withLogging(() => <div>Logged</div>);
// Dynamic hooks
const useDynamicHook = (hookName, ...args) => {
const hooks = {
useState: useState,
useEffect: useEffect,
useReducer: useReducer,
};
return hooks[hookName](...args);
};
// Dynamic imports
const loadComponent = async (path) => {
const module = await import(path);
return module.default;
};
// Creating components with React.createElement
const createElement = (type, props, ...children) => {
return React.createElement(type, props, ...children);
};
// Using React.cloneElement
const cloneElement = (element, props) => {
return React.cloneElement(element, props);
};
// Using React.Children utilities
const mapChildren = (children) => {
return React.Children.map(children, (child) => {
return child;
});
};
// Dynamic context creation
const createContext = (defaultValue) => {
return React.createContext(defaultValue);
};
const ThemeContext = createContext('light');
// Using forwardRef
const ForwardRefComponent = React.forwardRef((props, ref) => {
return <div ref={ref}>{props.children}</div>;
});
return (
<div>
<DynamicComponent>Dynamic</DynamicComponent>
<LoggedComponent />
<ThemeContext.Provider value="dark">
<div>Context Provider</div>
</ThemeContext.Provider>
<ForwardRefComponent>Forward Ref</ForwardRefComponent>
</div>
);
}Routing in React is implemented using React Router with BrowserRouter, Routes, and Route components.
- BrowserRouter: Router component
- Routes: Define route paths
- Route: Map path to component
- Link: Navigation links
- useNavigate: Programmatic navigation
// Interoperability with other Libraries
function InteropExample() {
// Using jQuery
useEffect(() => {
// @ts-ignore
import('jquery').then(($) => {
$('body').append('<p>jQuery loaded</p>');
});
}, []);
// Using D3
const d3Ref = useRef(null);
useEffect(() => {
if (d3Ref.current) {
import('d3').then((d3) => {
const svg = d3.select(d3Ref.current);
svg.append('circle')
.attr('cx', 50)
.attr('cy', 50)
.attr('r', 40)
.style('fill', 'blue');
});
}
}, []);
// Using Three.js
const threeRef = useRef(null);
useEffect(() => {
if (threeRef.current) {
import('three').then((THREE) => {
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, 1, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(400, 300);
threeRef.current.appendChild(renderer.domElement);
const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
camera.position.z = 5;
const animate = () => {
requestAnimationFrame(animate);
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render(scene, camera);
};
animate();
});
}
}, []);
// Using Chart.js
const chartRef = useRef(null);
useEffect(() => {
if (chartRef.current) {
import('chart.js').then((Chart) => {
new Chart.Chart(chartRef.current, {
type: 'bar',
data: {
labels: ['A', 'B', 'C'],
datasets: [{
data: [10, 20, 30]
}]
}
});
});
}
}, []);
// Using Leaflet for maps
const mapRef = useRef(null);
useEffect(() => {
if (mapRef.current) {
import('leaflet').then((L) => {
const map = L.map(mapRef.current).setView([51.505, -0.09], 13);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(map);
});
}
}, []);
return (
<div>
<h3>Interoperability</h3>
<svg ref={d3Ref} width={100} height={100}></svg>
<div ref={threeRef}></div>
<canvas ref={chartRef} width={400} height={200}></canvas>
<div ref={mapRef} style={{ width: 400, height: 300 }}></div>
</div>
);
}Lists in React are rendered using map() with keys for efficient reconciliation and re-rendering.
- Rendering:
items.map(item => <li key={item.id}>{item.name}</li>) - Keys: Unique identifiers for list items
- Reconciliation: Efficient DOM updates
- Sorting: Sort before rendering
- Filtering: Filter before rendering
// Performance Optimization in React
function PerformanceExample() {
// 1. useMemo for expensive computations
const expensiveCalculation = useMemo(() => {
let result = 0;
for (let i = 0; i < 1000000; i++) {
result += i;
}
return result;
}, []);
// 2. useCallback for function memoization
const handleClick = useCallback(() => {
console.log('Clicked');
}, []);
// 3. React.memo for component memoization
const MemoizedChild = React.memo(({ data }) => {
return <div>{data}</div>;
});
// 4. useTransition for non-blocking updates
const [isPending, startTransition] = useTransition();
const [count, setCount] = useState(0);
const handleUpdate = () => {
startTransition(() => {
setCount(c => c + 1);
});
};
// 5. useDeferredValue for deferred updates
const [input, setInput] = useState('');
const deferredInput = useDeferredValue(input);
// 6. Virtualization for large lists
// Using react-window
// import { FixedSizeList } from 'react-window';
// const Row = ({ index, style }) => <div style={style}>Row {index}</div>;
// <FixedSizeList height={400} itemCount={10000} itemSize={35}>
// {Row}
// </FixedSizeList>
// 7. Lazy loading
const LazyComponent = React.lazy(() => import('./LazyComponent'));
// 8. Code splitting
// Use dynamic imports for route-based splitting
// 9. Avoiding unnecessary re-renders
const [state, setState] = useState({ count: 0, other: 0 });
// Instead of:
// setState({ ...state, count: state.count + 1 });
// Use:
const incrementCount = () => {
setState(prev => ({ ...prev, count: prev.count + 1 }));
};
// 10. Using keys for list rendering
const items = ['A', 'B', 'C'];
// 11. Debouncing and throttling
const debounce = (fn, delay) => {
let timeoutId;
return (...args) => {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => fn(...args), delay);
};
};
const handleSearch = debounce((value) => {
console.log('Searching:', value);
}, 500);
// 12. Using React.Profiler
// <React.Profiler id="App" onRender={onRenderCallback}>
// <App />
// </React.Profiler>
return (
<div>
<h3>Performance Optimization</h3>
<p>Expensive: {expensiveCalculation}</p>
<button onClick={handleClick}>Click</button>
<MemoizedChild data="Memoized" />
<button onClick={handleUpdate}>Update ({count})</button>
<input
value={input}
onChange={(e) => setInput(e.target.value)}
placeholder="Search"
/>
<p>Deferred: {deferredInput}</p>
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
<ul>
{items.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
</div>
);
}Forms in React use controlled components with state management for form data and error handling.
- Controlled components: State controls input value
- Uncontrolled components: DOM handles value
- Validation: Validate on submit or change
- Error handling: Display error messages
- Submission: Handle form submission
// Networking in React
function NetworkingExample() {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
// Using fetch API
const fetchData = async () => {
setLoading(true);
try {
const response = await fetch('https://api.github.com');
const json = await response.json();
setData(json);
setError(null);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
};
// Using Axios
// npm install axios
import axios from 'axios';
const fetchWithAxios = async () => {
setLoading(true);
try {
const response = await axios.get('https://api.github.com');
setData(response.data);
setError(null);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
};
// POST request
const postData = async () => {
try {
const response = await fetch('https://httpbin.org/post', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ name: 'Alice', age: 25 }),
});
const json = await response.json();
console.log(json);
} catch (err) {
console.error(err);
}
};
// Using React Query
// npm install @tanstack/react-query
import { useQuery, useMutation } from '@tanstack/react-query';
const { data: queryData, isLoading, isError } = useQuery({
queryKey: ['github'],
queryFn: () => fetch('https://api.github.com').then(res => res.json()),
});
const mutation = useMutation({
mutationFn: (newData) => {
return fetch('https://httpbin.org/post', {
method: 'POST',
body: JSON.stringify(newData),
}).then(res => res.json());
},
});
// WebSocket
const [wsMessage, setWsMessage] = useState('');
useEffect(() => {
const ws = new WebSocket('wss://echo.websocket.org');
ws.onmessage = (event) => {
setWsMessage(event.data);
};
ws.onopen = () => {
ws.send('Hello WebSocket');
};
return () => ws.close();
}, []);
// Server-Sent Events
const [sseData, setSseData] = useState('');
useEffect(() => {
const eventSource = new EventSource('/events');
eventSource.onmessage = (event) => {
setSseData(event.data);
};
return () => eventSource.close();
}, []);
// GraphQL with Apollo Client
// npm install @apollo/client graphql
// import { gql, useQuery } from '@apollo/client';
// const GET_DATA = gql`
// query GetData {
// data {
// id
// name
// }
// }
// `;
// const { loading, error, data } = useQuery(GET_DATA);
return (
<div>
<h3>Networking</h3>
<button onClick={fetchData}>Fetch Data</button>
<button onClick={fetchWithAxios}>Fetch with Axios</button>
<button onClick={postData}>POST Data</button>
{loading && <p>Loading...</p>}
{error && <p>Error: {error}</p>}
{data && <pre>{JSON.stringify(data, null, 2).slice(0, 200)}</pre>}
<p>WebSocket: {wsMessage}</p>
<p>SSE: {sseData}</p>
</div>
);
}API integration in React uses fetch or axios with async/await for making HTTP requests and handling responses.
- fetch API: Native JavaScript API
- axios: Third-party library
- async/await: Handle async operations
- Error handling: Try-catch blocks
- Loading states: Show loading indicators
// Working with JSON in React
function JsonExample() {
const [jsonData, setJsonData] = useState(null);
const [jsonString, setJsonString] = useState('');
// Encode to JSON
const data = {
name: 'Alice',
age: 25,
city: 'NYC',
hobbies: ['reading', 'coding'],
};
const jsonStringified = JSON.stringify(data);
const prettyJson = JSON.stringify(data, null, 2);
// Decode from JSON
const jsonStr = '{"name":"Bob","age":30,"city":"LA"}';
const parsed = JSON.parse(jsonStr);
// Working with arrays
const jsonArray = JSON.stringify([1, 2, 3, 4, 5]);
const parsedArray = JSON.parse(jsonArray);
// Nested structures
const nested = {
user: {
id: 1,
profile: {
name: 'Alice',
email: 'alice@example.com',
},
},
};
const nestedJson = JSON.stringify(nested, null, 2);
// Reading JSON from file
const handleFileUpload = (event) => {
const file = event.target.files[0];
const reader = new FileReader();
reader.onload = (e) => {
try {
const data = JSON.parse(e.target.result);
setJsonData(data);
} catch (err) {
console.error('Invalid JSON:', err);
}
};
reader.readAsText(file);
};
// Writing JSON to file
const downloadJson = () => {
const data = { name: 'Alice', age: 25 };
const json = JSON.stringify(data, null, 2);
const blob = new Blob([json], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'data.json';
a.click();
URL.revokeObjectURL(url);
};
// Error handling
const safeJsonParse = (str) => {
try {
return JSON.parse(str);
} catch (e) {
console.error('JSON parse error:', e);
return null;
}
};
// Custom JSON serialization
class User {
constructor(name, age) {
this.name = name;
this.age = age;
}
toJSON() {
return {
fullname: this.name,
years: this.age,
};
}
}
const user = new User('Alice', 25);
const userJson = JSON.stringify(user);
return (
<div>
<h3>JSON</h3>
<p>Stringified: {jsonStringified}</p>
<p>Pretty: <pre>{prettyJson}</pre></p>
<p>Parsed: {parsed.name}, {parsed.age}</p>
<p>Nested: <pre>{nestedJson}</pre></p>
<input type="file" accept=".json" onChange={handleFileUpload} />
<button onClick={downloadJson}>Download JSON</button>
{jsonData && <pre>{JSON.stringify(jsonData, null, 2)}</pre>}
<p>User JSON: {userJson}</p>
</div>
);
}Modals in React are created using custom Modal components with portals for overlay and z-index management.
- Modal component: Custom modal with overlay
- Portals: Render outside parent DOM
- State control: Open/close state
- Animation: Transition animations
- Accessibility: Focus management
// Testing in React
// Using Jest and React Testing Library
// npm install --save-dev @testing-library/react @testing-library/jest-dom
// Component to test
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
// Test file (Counter.test.jsx)
/*
import { render, screen, fireEvent } from '@testing-library/react';
import '@testing-library/jest-dom';
import Counter from './Counter';
describe('Counter', () => {
test('renders initial count', () => {
render(<Counter />);
expect(screen.getByText('Count: 0')).toBeInTheDocument();
});
test('increments count on button click', () => {
render(<Counter />);
const button = screen.getByText('Increment');
fireEvent.click(button);
expect(screen.getByText('Count: 1')).toBeInTheDocument();
});
});
*/
// Testing hooks
/*
import { renderHook, act } from '@testing-library/react';
function useCounter(initial = 0) {
const [count, setCount] = useState(initial);
const increment = () => setCount(c => c + 1);
return { count, increment };
}
describe('useCounter', () => {
test('returns initial count', () => {
const { result } = renderHook(() => useCounter(5));
expect(result.current.count).toBe(5);
});
test('increments count', () => {
const { result } = renderHook(() => useCounter());
act(() => {
result.current.increment();
});
expect(result.current.count).toBe(1);
});
});
*/
// Testing async code
/*
import { waitFor } from '@testing-library/react';
test('fetches data', async () => {
render(<DataFetcher />);
await waitFor(() => {
expect(screen.getByText('Data loaded')).toBeInTheDocument();
});
});
*/
// Testing with mock functions
/*
const mockFetch = jest.fn();
mockFetch.mockResolvedValue({ data: 'test' });
test('calls fetch', async () => {
render(<DataComponent fetchData={mockFetch} />);
expect(mockFetch).toHaveBeenCalled();
});
*/
// Testing with user events
/*
import userEvent from '@testing-library/user-event';
test('user interaction', async () => {
const user = userEvent.setup();
render(<Form />);
await user.type(screen.getByLabelText('Name'), 'Alice');
await user.click(screen.getByText('Submit'));
expect(screen.getByText('Submitted')).toBeInTheDocument();
});
*/
// Testing with snapshot
/*
test('renders correctly', () => {
const { container } = render(<Component />);
expect(container).toMatchSnapshot();
});
*/
// Testing context
/*
const TestWrapper = ({ children }) => (
<ThemeProvider value="dark">{children}</ThemeProvider>
);
test('uses context', () => {
render(<Consumer />, { wrapper: TestWrapper });
expect(screen.getByText('dark')).toBeInTheDocument();
});
*/Styling in React can be done using CSS Modules, Styled Components, Tailwind CSS, or inline styles.
- CSS Modules: Scoped CSS
- Styled Components: CSS-in-JS
- Tailwind CSS: Utility-first CSS
- Inline styles:
style={{ color: 'red' }} - Theming: Dark mode support
// Debugging in React
function DebuggingExample() {
const [value, setValue] = useState('');
// 1. Console logging
console.log('Component rendered');
// 2. Using debugger statement
const handleClick = () => {
debugger;
setValue('Clicked');
};
// 3. React DevTools
// Install React DevTools extension
// Use Components tab to inspect component tree
// Use Profiler tab to analyze performance
// 4. Using useEffect for debugging
useEffect(() => {
console.log('Component mounted');
return () => console.log('Component unmounted');
}, []);
useEffect(() => {
console.log('Value changed:', value);
}, [value]);
// 5. Using useDebugValue
const useCustomHook = (value) => {
useDebugValue(value, (v) => `Custom: ${v}`);
return value;
};
const debugValue = useCustomHook('test');
// 6. Error boundaries for debugging
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false, error: null };
}
static getDerivedStateFromError(error) {
return { hasError: true, error };
}
componentDidCatch(error, errorInfo) {
console.error('Error:', error);
console.error('Error Info:', errorInfo);
}
render() {
if (this.state.hasError) {
return <div>Error: {this.state.error?.message}</div>;
}
return this.props.children;
}
}
// 7. Using breakpoints in browser
// Set breakpoints in Sources tab
// 8. React Profiler for performance debugging
// <React.Profiler id="App" onRender={onRender}>
// <App />
// </React.Profiler>
const onRender = (id, phase, actualDuration) => {
console.log(`${id} ${phase} took ${actualDuration}ms`);
};
// 9. Using why-did-you-render
// npm install @welldone-software/why-did-you-render
/*
import whyDidYouRender from '@welldone-software/why-did-you-render';
whyDidYouRender(React, { trackAllPureComponents: true });
*/
// 10. Logging props with useEffect
const logProps = (props) => {
useEffect(() => {
console.log('Props:', props);
}, [props]);
};
return (
<ErrorBoundary>
<div>
<h3>Debugging</h3>
<input
value={value}
onChange={(e) => setValue(e.target.value)}
placeholder="Type something"
/>
<button onClick={handleClick}>Click me</button>
<p>Value: {value}</p>
<p>Debug value: {debugValue}</p>
</div>
</ErrorBoundary>
);
}Reverse a string using JavaScript methods or manual iteration.
- Built-in:
str.split('').reverse().join('') - Manual: Iterate from end to start
- Using spread:
[...str].reverse().join('') - Complexity: O(n) time
// Abstract Components and Interfaces in React
// Abstract component pattern
function AbstractComponent({ children, render, ...props }) {
// This component doesn't render anything directly
// It provides a common interface for child components
return children({ ...props });
}
// Usage
<AbstractComponent data={[1, 2, 3]}>
{({ data }) => (
<ul>
{data.map(item => <li key={item}>{item}</li>)}
</ul>
)}
</AbstractComponent>
// Interface using PropTypes (or TypeScript)
import PropTypes from 'prop-types';
const ComponentWithInterface = ({ name, age, city }) => {
return <div>{name} ({age}) from {city}</div>;
};
ComponentWithInterface.propTypes = {
name: PropTypes.string.isRequired,
age: PropTypes.number.isRequired,
city: PropTypes.string,
};
// TypeScript interface
interface PersonProps {
name: string;
age: number;
city?: string;
}
const PersonComponent: React.FC<PersonProps> = ({ name, age, city = 'Unknown' }) => {
return <div>{name} ({age}) from {city}</div>;
};
// Abstract class component
abstract class BaseComponent<P = {}, S = {}> extends React.Component<P, S> {
abstract render(): React.ReactNode;
componentDidMount() {
this.onMount();
}
protected onMount(): void {
// Optional lifecycle hook
}
}
// Concrete implementation
class ConcreteComponent extends BaseComponent {
render() {
return <div>Concrete</div>;
}
}
// Render props pattern for abstraction
const DataProvider = ({ children, fetch }) => {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(false);
useEffect(() => {
setLoading(true);
fetch().then(result => {
setData(result);
setLoading(false);
});
}, [fetch]);
return children({ data, loading });
};
// Usage
<DataProvider fetch={() => fetch('/api/data')}>
{({ data, loading }) => (
loading ? <p>Loading...</p> : <pre>{JSON.stringify(data)}</pre>
)}
</DataProvider>Check if a string is a palindrome using JavaScript methods or two-pointer approach.
- Built-in:
str === str.split('').reverse().join('') - Two-pointer: Compare from both ends
- Case insensitive:
toLowerCase() - Ignoring non-alphanumeric:
replace(/[^a-z0-9]/g, '')
// Generic Components in React (TypeScript)
// Generic component
interface ListProps<T> {
items: T[];
renderItem: (item: T, index: number) => React.ReactNode;
keyExtractor?: (item: T) => string;
}
function List<T>({ items, renderItem, keyExtractor }: ListProps<T>) {
return (
<ul>
{items.map((item, index) => (
<li key={keyExtractor ? keyExtractor(item) : index}>
{renderItem(item, index)}
</li>
))}
</ul>
);
}
// Usage
<List
items={[{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }]}
renderItem={(item) => <span>{item.name}</span>}
keyExtractor={(item) => String(item.id)}
/>
// Generic hook
function useFetch<T>(url: string): { data: T | null; loading: boolean } {
const [data, setData] = useState<T | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch(url)
.then(res => res.json())
.then((result: T) => {
setData(result);
setLoading(false);
});
}, [url]);
return { data, loading };
}
// Usage
interface User {
id: number;
name: string;
}
const { data, loading } = useFetch<User[]>('/api/users');
// Generic context
interface ContextValue<T> {
data: T;
updateData: (newData: T) => void;
}
function createGenericContext<T>() {
return React.createContext<ContextValue<T> | null>(null);
}
// Generic provider
function GenericProvider<T>({ children, initialData }: { children: React.ReactNode; initialData: T }) {
const [data, setData] = useState(initialData);
const value = { data, updateData: setData };
return <Context.Provider value={value}>{children}</Context.Provider>;
}
// Generic hoc
function withData<T, P extends { data?: T }>(
Component: React.ComponentType<P>
) {
return function WithData(props: Omit<P, 'data'> & { data: T }) {
return <Component {...props as P} data={props.data} />;
};
}Find maximum value using Math.max or manual iteration.
- Built-in:
Math.max.apply(null, arr) - Spread:
Math.max(...arr) - Manual: Iterate and track max
- Complexity: O(n) time
// HOC and Render Props in React
// Higher-Order Component
function withLoading(WrappedComponent) {
return function WithLoading({ isLoading, ...props }) {
if (isLoading) {
return <div>Loading...</div>;
}
return <WrappedComponent {...props} />;
};
}
// Usage
const UserListWithLoading = withLoading(UserList);
// HOC with state
function withCounter(WrappedComponent) {
return function WithCounter(props) {
const [count, setCount] = useState(0);
const increment = () => setCount(c => c + 1);
return <WrappedComponent {...props} count={count} increment={increment} />;
};
}
// HOC for logging
function withLogging(WrappedComponent) {
return function WithLogging(props) {
useEffect(() => {
console.log(`${WrappedComponent.name} mounted`);
return () => console.log(`${WrappedComponent.name} unmounted`);
}, []);
return <WrappedComponent {...props} />;
};
}
// Render Props pattern
class DataProvider extends React.Component {
state = { data: null, loading: false };
componentDidMount() {
this.setState({ loading: true });
this.props.fetch()
.then(data => this.setState({ data, loading: false }));
}
render() {
return this.props.children(this.state);
}
}
// Usage
<DataProvider fetch={() => fetch('/api/data')}>
{({ data, loading }) => (
loading ? <p>Loading...</p> : <pre>{JSON.stringify(data)}</pre>
)}
</DataProvider>
// Render Props with multiple children
function Toggle({ children }) {
const [on, setOn] = useState(false);
const toggle = () => setOn(!on);
return children({ on, toggle });
}
// Usage
<Toggle>
{({ on, toggle }) => (
<div>
<button onClick={toggle}>{on ? 'ON' : 'OFF'}</button>
{on && <p>Visible</p>}
</div>
)}
</Toggle>
// Compose multiple HOCs
const compose = (...hocs) => (Component) => {
return hocs.reduceRight((acc, hoc) => hoc(acc), Component);
};
const EnhancedComponent = compose(
withLoading,
withCounter,
withLogging
)(BaseComponent);Remove duplicates using Set or filter method.
- Set:
[...new Set(arr)] - Filter:
arr.filter((item, index) => arr.indexOf(item) === index) - Preserve order: Set preserves insertion order
- Complexity: O(n) time
// Generators and Coroutines in React
function GeneratorExample() {
// Generator function
function* fibonacciGenerator() {
let a = 0, b = 1;
while (true) {
yield a;
[a, b] = [b, a + b];
}
}
const fib = fibonacciGenerator();
const fibNumbers = Array.from({ length: 10 }, () => fib.next().value);
// Generator with state
function* counterGenerator(start = 0) {
let i = start;
while (true) {
yield i++;
}
}
const counter = counterGenerator(1);
const counts = Array.from({ length: 5 }, () => counter.next().value);
// Coroutine using generator
function* coroutine() {
let state = 0;
while (true) {
const input = yield state;
state += input || 1;
}
}
const coro = coroutine();
coro.next(); // Start
const result1 = coro.next(5).value; // 5
const result2 = coro.next(10).value; // 15
// Using async/await (similar to coroutines)
const fetchData = async () => {
const response = await fetch('/api/data');
const data = await response.json();
return data;
};
// Using generators for lazy evaluation
function* lazyRange(start, end) {
for (let i = start; i < end; i++) {
yield i;
}
}
const range = lazyRange(0, 1000000);
const firstTen = Array.from({ length: 10 }, () => range.next().value);
// Generator for infinite sequence
function* infiniteSequence() {
let i = 0;
while (true) {
yield i++;
}
}
// Using generator for pagination
function* paginate(data, pageSize) {
for (let i = 0; i < data.length; i += pageSize) {
yield data.slice(i, i + pageSize);
}
}
const pages = paginate([1,2,3,4,5,6,7,8,9,10], 3);
const page1 = pages.next().value;
return (
<div>
<h3>Generators</h3>
<p>Fibonacci: {fibNumbers.join(', ')}</p>
<p>Counter: {counts.join(', ')}</p>
<p>Coroutine: {result1}, {result2}</p>
<p>First 10 from range: {firstTen.join(', ')}</p>
<p>Page 1: {page1.join(', ')}</p>
</div>
);
}Merge arrays using concat or spread operator.
- concat:
arr1.concat(arr2) - Spread:
[...arr1, ...arr2] - Unique merge:
[...new Set([...arr1, ...arr2])] - Complexity: O(n) time
// Advanced Array Operations in React
function AdvancedArrayExample() {
// Array initialization
const zeros = Array(3).fill(0);
const ones = Array(3).fill(1);
const identity = Array.from({ length: 3 }, (_, i) =>
Array.from({ length: 3 }, (_, j) => i === j ? 1 : 0)
);
// Reshaping
const flat = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const reshaped = Array.from({ length: 3 }, (_, i) =>
flat.slice(i * 3, i * 3 + 3)
);
// Transpose
const matrix = [[1,2,3], [4,5,6], [7,8,9]];
const transposed = matrix[0].map((_, colIndex) =>
matrix.map(row => row[colIndex])
);
// Element-wise operations
const A = [[1,2,3], [4,5,6], [7,8,9]];
const B = A.map(row => row.map(x => x + 1));
const C = A.map(row => row.map(x => x * 2));
const D = A.map(row => row.map(x => x * x));
// Matrix multiplication
const matMul = (A, B) => {
const rows = A.length;
const cols = B[0].length;
const inner = B.length;
const result = Array.from({ length: rows }, () => Array(cols).fill(0));
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
for (let k = 0; k < inner; k++) {
result[i][j] += A[i][k] * B[k][j];
}
}
}
return result;
};
const X = Array.from({ length: 3 }, () => Array.from({ length: 3 }, () => Math.random()));
const Y = Array.from({ length: 3 }, () => Array.from({ length: 3 }, () => Math.random()));
const Z = matMul(X, Y);
// Element-wise multiplication
const W = X.map((row, i) => row.map((val, j) => val * Y[i][j]));
// Matrix norm (Frobenius)
const norm = (matrix) => {
let sum = 0;
for (const row of matrix) {
for (const val of row) {
sum += val * val;
}
}
return Math.sqrt(sum);
};
// Trace
const trace = (matrix) => {
let sum = 0;
for (let i = 0; i < matrix.length; i++) {
sum += matrix[i][i];
}
return sum;
};
// Diagonal
const diag = (matrix) => {
return matrix.map((row, i) => row[i]);
};
return (
<div>
<h3>Advanced Arrays</h3>
<p>Identity: {JSON.stringify(identity)}</p>
<p>Reshaped: {JSON.stringify(reshaped)}</p>
<p>Transposed: {JSON.stringify(transposed)}</p>
<p>Norm: {norm(X).toFixed(2)}</p>
<p>Trace: {trace(X).toFixed(2)}</p>
<p>Diagonal: {diag(X).map(x => x.toFixed(2)).join(', ')}</p>
</div>
);
}Convert string to number using parseInt, parseFloat, or Number.
- parseInt:
parseInt(str, 10) - parseFloat:
parseFloat(str) - Number:
Number(str) - Safe conversion: Check with
isNaN
// Handling Missing Data in React
function MissingDataExample() {
// Using null and undefined
const data = [1, 2, null, 4, 5, undefined, 7];
// Check for missing values
const hasMissing = data.some(x => x === null || x === undefined);
// Remove missing values
const cleanData = data.filter(x => x !== null && x !== undefined);
// Replace missing values
const replaced = data.map(x => x ?? 0);
// Operations with missing values
const x = [1, 2, null, 4];
const y = [5, 6, null, 8];
const z = x.map((val, i) => {
if (val !== null && y[i] !== null) {
return val + y[i];
}
return null;
});
// Ignoring missing values
const sumComplete = x
.filter(val => val !== null)
.reduce((acc, val) => acc + val, 0);
// Optional values in objects
interface User {
name: string;
age?: number;
city?: string;
}
const user: User = { name: 'Alice' };
const age = user.age ?? 0;
// Nullish coalescing in JSX
const displayValue = (value: string | null | undefined) => {
return value ?? 'N/A';
};
// Optional chaining
const getUserCity = (user: User | null) => {
return user?.city ?? 'Unknown';
};
// Default props for missing data
const ComponentWithDefaults = ({ name = 'Guest', age = 0 }) => {
return <div>{name} ({age})</div>;
};
// Loading state for missing data
const [loading, setLoading] = useState(true);
const [userData, setUserData] = useState(null);
if (loading) return <div>Loading...</div>;
if (!userData) return <div>No data available</div>;
return (
<div>
<h3>Missing Data</h3>
<p>Original: {data.join(', ')}</p>
<p>Has missing: {String(hasMissing)}</p>
<p>Clean: {cleanData.join(', ')}</p>
<p>Replaced: {replaced.join(', ')}</p>
<p>Sum: {sumComplete}</p>
<p>User city: {getUserCity(null)}</p>
<ComponentWithDefaults />
</div>
);
}Iterate through object using for...in, Object.keys, or Object.entries.
- for...in:
for (var key in obj) - Object.keys:
Object.keys(obj).forEach - Object.entries:
Object.entries(obj).forEach - hasOwnProperty: Check for own properties
// Sorting and Searching in React
function SortingSearchingExample() {
const [data, setData] = useState([5, 2, 8, 1, 9, 3]);
const [searchTerm, setSearchTerm] = useState('');
// Basic sorting
const sortedAsc = [...data].sort((a, b) => a - b);
const sortedDesc = [...data].sort((a, b) => b - a);
// Sorting objects
const objects = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
{ name: 'Charlie', age: 35 },
];
const sortedByAge = [...objects].sort((a, b) => a.age - b.age);
const sortedByName = [...objects].sort((a, b) => a.name.localeCompare(b.name));
// Custom sorting
const customSort = (arr, key) => {
return [...arr].sort((a, b) => {
if (a[key] < b[key]) return -1;
if (a[key] > b[key]) return 1;
return 0;
});
};
// Searching
const searchGreaterThan = (arr, threshold) => {
return arr.filter(x => x > threshold);
};
const findFirstGreater = (arr, threshold) => {
return arr.find(x => x > threshold) || null;
};
const findLastGreater = (arr, threshold) => {
return [...arr].reverse().find(x => x > threshold) || null;
};
// Binary search
const binarySearch = (arr, target) => {
let left = 0;
let right = arr.length - 1;
while (left <= right) {
const mid = Math.floor((left + right) / 2);
if (arr[mid] === target) return mid;
if (arr[mid] < target) left = mid + 1;
else right = mid - 1;
}
return -1;
};
const sortedData = [...data].sort((a, b) => a - b);
const searchIndex = binarySearch(sortedData, 5);
// Contains
const hasSeven = data.includes(7);
const hasFour = data.includes(4);
// Filter with search term
const filteredData = data.filter(x =>
String(x).includes(searchTerm)
);
return (
<div>
<h3>Sorting and Searching</h3>
<p>Original: {data.join(', ')}</p>
<p>Sorted Asc: {sortedAsc.join(', ')}</p>
<p>Sorted Desc: {sortedDesc.join(', ')}</p>
<p>Sorted by age: {sortedByAge.map(x => x.name).join(', ')}</p>
<p>Greater than 5: {searchGreaterThan(data, 5).join(', ')}</p>
<p>First greater than 5: {findFirstGreater(data, 5)}</p>
<p>Last greater than 5: {findLastGreater(data, 5)}</p>
<p>Binary search index for 5: {searchIndex}</p>
<p>Has 7: {String(hasSeven)}, Has 4: {String(hasFour)}</p>
<input
type="text"
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
placeholder="Search"
/>
<p>Filtered: {filteredData.join(', ')}</p>
</div>
);
}Delay execution using setTimeout, setInterval, or Promises.
- setTimeout:
setTimeout(fn, delay) - setInterval:
setInterval(fn, interval) - Promise:
new Promise(resolve => setTimeout(resolve, delay)) - async/await:
await delay(1000)
// Mathematical Operations in React
function MathExample() {
// Basic arithmetic
const x = 10, y = 3;
const results = {
add: x + y,
subtract: x - y,
multiply: x * y,
divide: x / y,
modulo: x % y,
power: Math.pow(x, y),
};
// Mathematical functions
const pi = Math.PI;
const trig = {
sin: Math.sin(pi / 4),
cos: Math.cos(pi / 4),
tan: Math.tan(pi / 4),
exp: Math.exp(1),
log: Math.log(Math.E),
log10: Math.log10(100),
sqrt: Math.sqrt(9),
};
// Special functions
const special = {
abs: Math.abs(-5),
ceil: Math.ceil(3.14),
floor: Math.floor(3.14),
round: Math.round(3.14),
max: Math.max(1, 3, 5, 2, 4),
min: Math.min(1, 3, 5, 2, 4),
};
// Random numbers
const random = {
random: Math.random(),
int: Math.floor(Math.random() * 10) + 1,
};
// Statistics
const data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const stats = {
sum: data.reduce((a, b) => a + b, 0),
mean: data.reduce((a, b) => a + b, 0) / data.length,
min: Math.min(...data),
max: Math.max(...data),
};
// Linear algebra
const matrixMul = (A, B) => {
const result = [];
for (let i = 0; i < A.length; i++) {
result[i] = [];
for (let j = 0; j < B[0].length; j++) {
let sum = 0;
for (let k = 0; k < B.length; k++) {
sum += A[i][k] * B[k][j];
}
result[i][j] = sum;
}
}
return result;
};
const A = [[1, 2], [3, 4]];
const B = [[5, 6], [7, 8]];
const product = matrixMul(A, B);
return (
<div>
<h3>Mathematical Operations</h3>
<p>Add: {results.add}, Subtract: {results.subtract}</p>
<p>Multiply: {results.multiply}, Divide: {results.divide}</p>
<p>Modulo: {results.modulo}, Power: {results.power}</p>
<p>Sin(pi/4): {trig.sin.toFixed(4)}</p>
<p>Exp(1): {trig.exp.toFixed(4)}</p>
<p>Abs(-5): {special.abs}</p>
<p>Random: {random.random.toFixed(4)}</p>
<p>Sum: {stats.sum}, Mean: {stats.mean}</p>
<p>Matrix product: {JSON.stringify(product)}</p>
</div>
);
}Make HTTP GET requests using fetch, axios, or XMLHttpRequest.
- fetch:
fetch(url).then(res => res.json()) - axios:
axios.get(url).then(res => res.data) - async/await:
const response = await fetch(url) - Error handling: Check response status
// Data Serialization in React
function SerializationExample() {
// JSON serialization
const data = {
name: 'Alice',
age: 25,
hobbies: ['reading', 'coding'],
address: {
city: 'NYC',
zip: '10001',
},
};
const jsonString = JSON.stringify(data);
const prettyJson = JSON.stringify(data, null, 2);
const parsedData = JSON.parse(jsonString);
// Custom serialization
class User {
constructor(name, age) {
this.name = name;
this.age = age;
}
toJSON() {
return {
fullName: this.name,
years: this.age,
type: 'user',
};
}
static fromJSON(json) {
const { fullName, years } = JSON.parse(json);
return new User(fullName, years);
}
}
const user = new User('Alice', 25);
const userJson = JSON.stringify(user);
const restoredUser = User.fromJSON(userJson);
// Serialization with date
const withDate = {
name: 'Event',
date: new Date(),
};
const dateJson = JSON.stringify(withDate, (key, value) => {
if (value instanceof Date) {
return { __type: 'Date', value: value.toISOString() };
}
return value;
});
// Deserialize with date
const parsedWithDate = JSON.parse(dateJson, (key, value) => {
if (value && value.__type === 'Date') {
return new Date(value.value);
}
return value;
});
// Serialization with circular references
const circular = { name: 'Circular' };
circular.self = circular;
const circularJson = JSON.stringify(circular, (key, value) => {
if (key === 'self' && value === circular) {
return '[Circular]';
}
return value;
});
// Using FormData for form serialization
const formData = new FormData();
formData.append('name', 'Alice');
formData.append('age', '25');
// URL encoding
const urlEncoded = new URLSearchParams({
name: 'Alice',
age: '25',
}).toString();
// Query string parsing
const queryString = '?name=Alice&age=25';
const params = new URLSearchParams(queryString);
const parsedParams = {
name: params.get('name'),
age: params.get('age'),
};
return (
<div>
<h3>Serialization</h3>
<p>JSON: {jsonString}</p>
<p>Pretty: <pre>{prettyJson}</pre></p>
<p>User JSON: {userJson}</p>
<p>URL Encoded: {urlEncoded}</p>
<p>Query params: {JSON.stringify(parsedParams)}</p>
</div>
);
}Create a Deferred using Promises or custom implementation with resolve and reject functions.
- Promise:
new Promise((resolve, reject) => {}) - Custom Deferred: Object with resolve/reject
- then method: Handle fulfillment and rejection
- Chain:
then().catch()
// Interfacing with External Systems in React
function ExternalSystemsExample() {
// Local Storage
const [storageValue, setStorageValue] = useState('');
const saveToStorage = () => {
localStorage.setItem('key', storageValue);
};
const loadFromStorage = () => {
const value = localStorage.getItem('key');
setStorageValue(value || '');
};
// Session Storage
const saveToSession = () => {
sessionStorage.setItem('key', storageValue);
};
// Cookies
const setCookie = (name, value, days) => {
const expires = new Date();
expires.setDate(expires.getDate() + days);
document.cookie = `${name}=${value};expires=${expires.toUTCString()}`;
};
const getCookie = (name) => {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length === 2) {
return parts.pop().split(';').shift();
}
};
// IndexedDB
const openDB = () => {
return new Promise((resolve, reject) => {
const request = indexedDB.open('MyDatabase', 1);
request.onupgradeneeded = (event) => {
const db = event.target.result;
db.createObjectStore('users', { keyPath: 'id' });
};
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
};
const saveToDB = async (data) => {
const db = await openDB();
const transaction = db.transaction(['users'], 'readwrite');
const store = transaction.objectStore('users');
store.put(data);
};
// Web Bluetooth
const connectBluetooth = async () => {
try {
const device = await navigator.bluetooth.requestDevice({
acceptAllDevices: true,
});
const server = await device.gatt.connect();
console.log('Connected:', device.name);
} catch (error) {
console.error('Bluetooth error:', error);
}
};
// Web USB
const connectUSB = async () => {
try {
const device = await navigator.usb.requestDevice({ filters: [] });
await device.open();
console.log('USB device connected');
} catch (error) {
console.error('USB error:', error);
}
};
// Clipboard API
const copyToClipboard = async (text) => {
try {
await navigator.clipboard.writeText(text);
console.log('Copied to clipboard');
} catch (error) {
console.error('Clipboard error:', error);
}
};
// Geolocation
const getLocation = () => {
return new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition(resolve, reject);
});
};
const [location, setLocation] = useState(null);
const fetchLocation = async () => {
try {
const position = await getLocation();
setLocation({
latitude: position.coords.latitude,
longitude: position.coords.longitude,
});
} catch (error) {
console.error('Geolocation error:', error);
}
};
// Web Speech API
const speak = (text) => {
const utterance = new SpeechSynthesisUtterance(text);
window.speechSynthesis.speak(utterance);
};
return (
<div>
<h3>External Systems</h3>
<input
value={storageValue}
onChange={(e) => setStorageValue(e.target.value)}
placeholder="Enter value"
/>
<button onClick={saveToStorage}>Save to Storage</button>
<button onClick={loadFromStorage}>Load from Storage</button>
<button onClick={saveToSession}>Save to Session</button>
<button onClick={() => setCookie('key', storageValue, 7)}>Set Cookie</button>
<button onClick={() => copyToClipboard(storageValue)}>Copy</button>
<button onClick={connectBluetooth}>Connect Bluetooth</button>
<button onClick={connectUSB}>Connect USB</button>
<button onClick={fetchLocation}>Get Location</button>
<button onClick={() => speak(storageValue)}>Speak</button>
{location && <p>Location: {location.latitude}, {location.longitude}</p>}
</div>
);
}Calculate factorial using recursion or iteration.
- Recursive:
n * factorial(n-1) - Iterative: Loop with multiplication
- Base case:
n <= 1 - Edge cases: 0! = 1
// Reverse a string in React
function ReverseString() {
const [input, setInput] = useState('hello');
const [reversed, setReversed] = useState('');
const reverseString = (s) => {
return s.split('').reverse().join('');
};
const reverseStringManual = (s) => {
let result = '';
for (let i = s.length - 1; i >= 0; i--) {
result += s[i];
}
return result;
};
const reverseStringRecursive = (s) => {
if (s.length <= 1) return s;
return reverseStringRecursive(s.slice(1)) + s[0];
};
const handleReverse = () => {
setReversed(reverseString(input));
};
return (
<div>
<h3>Reverse String</h3>
<input
value={input}
onChange={(e) => setInput(e.target.value)}
placeholder="Enter text"
/>
<button onClick={handleReverse}>Reverse</button>
<p>Original: {input}</p>
<p>Reversed: {reversed}</p>
<p>Manual: {reverseStringManual(input)}</p>
<p>Recursive: {reverseStringRecursive(input)}</p>
</div>
);
}Calculate Fibonacci using recursion, iteration, or memoization.
- Recursive:
fib(n-1) + fib(n-2) - Iterative: Loop with variables
- Memoization: Cache results in object
- Complexity: O(n) with memoization
// Check palindrome in React
function PalindromeChecker() {
const [input, setInput] = useState('racecar');
const [isPalindrome, setIsPalindrome] = useState(false);
const checkPalindrome = (s) => {
const cleaned = s.toLowerCase().replace(/\s/g, '');
return cleaned === cleaned.split('').reverse().join('');
};
const checkPalindromeManual = (s) => {
const cleaned = s.toLowerCase().replace(/\s/g, '');
for (let i = 0; i < cleaned.length / 2; i++) {
if (cleaned[i] !== cleaned[cleaned.length - 1 - i]) {
return false;
}
}
return true;
};
const checkPalindromeRecursive = (s) => {
const cleaned = s.toLowerCase().replace(/\s/g, '');
if (cleaned.length <= 1) return true;
if (cleaned[0] !== cleaned[cleaned.length - 1]) return false;
return checkPalindromeRecursive(cleaned.slice(1, -1));
};
const handleCheck = () => {
setIsPalindrome(checkPalindrome(input));
};
return (
<div>
<h3>Palindrome Checker</h3>
<input
value={input}
onChange={(e) => setInput(e.target.value)}
placeholder="Enter text"
/>
<button onClick={handleCheck}>Check</button>
<p>"{input}" is palindrome: {String(isPalindrome)}</p>
<p>Manual: {String(checkPalindromeManual(input))}</p>
<p>Recursive: {String(checkPalindromeRecursive(input))}</p>
</div>
);
}FizzBuzz using if-else or switch statement.
- Modulo:
i % 15 === 0 - Order: Check 15 first
- Range:
for (var i = 1; i <= n; i++) - Return array: Collect results
// Find max in array in React
function FindMax() {
const [array, setArray] = useState([1, 5, 3, 9, 2]);
const [max, setMax] = useState(null);
const findMax = (arr) => {
return Math.max(...arr);
};
const findMaxManual = (arr) => {
if (arr.length === 0) return null;
let max = arr[0];
for (const val of arr) {
if (val > max) max = val;
}
return max;
};
const findMaxRecursive = (arr, index = 0, maxVal = null) => {
if (index >= arr.length) return maxVal;
if (maxVal === null || arr[index] > maxVal) {
maxVal = arr[index];
}
return findMaxRecursive(arr, index + 1, maxVal);
};
const handleFind = () => {
setMax(findMax(array));
};
const addRandom = () => {
const random = Math.floor(Math.random() * 20) + 1;
setArray([...array, random]);
};
return (
<div>
<h3>Find Max</h3>
<p>Array: {array.join(', ')}</p>
<button onClick={addRandom}>Add Random</button>
<button onClick={handleFind}>Find Max</button>
<p>Max: {max}</p>
<p>Manual: {findMaxManual(array)}</p>
<p>Recursive: {findMaxRecursive(array)}</p>
</div>
);
}Find missing number using formula or XOR method.
- Formula:
total - sum - XOR: XOR all numbers and indices
- Complexity: O(n) time
- Edge cases: Empty array, missing first or last
// Remove duplicates in React
function RemoveDuplicates() {
const [array, setArray] = useState(['apple', 'banana', 'apple', 'orange', 'banana', 'grape']);
const [unique, setUnique] = useState([]);
const removeDuplicates = (arr) => {
return [...new Set(arr)];
};
const removeDuplicatesManual = (arr) => {
const seen = [];
const result = [];
for (const val of arr) {
if (!seen.includes(val)) {
seen.push(val);
result.push(val);
}
}
return result;
};
const removeDuplicatesFilter = (arr) => {
return arr.filter((val, index) => arr.indexOf(val) === index);
};
const handleRemove = () => {
setUnique(removeDuplicates(array));
};
return (
<div>
<h3>Remove Duplicates</h3>
<p>Original: {array.join(', ')}</p>
<button onClick={handleRemove}>Remove Duplicates</button>
<p>Unique: {unique.join(', ')}</p>
<p>Manual: {removeDuplicatesManual(array).join(', ')}</p>
<p>Filter: {removeDuplicatesFilter(array).join(', ')}</p>
</div>
);
}Find duplicates using Set or filter method.
- Set: Track seen elements
- Filter:
arr.filter((item, index) => arr.indexOf(item) !== index) - Counter: Object to count occurrences
- Complexity: O(n) time
// Merge arrays in React
function MergeArrays() {
const [arr1, setArr1] = useState([1, 2, 3]);
const [arr2, setArr2] = useState([4, 5, 6]);
const [merged, setMerged] = useState([]);
const mergeArrays = (a, b) => {
return [...a, ...b];
};
const mergeSorted = (a, b) => {
const result = [];
let i = 0, j = 0;
while (i < a.length && j < b.length) {
if (a[i] <= b[j]) {
result.push(a[i++]);
} else {
result.push(b[j++]);
}
}
while (i < a.length) result.push(a[i++]);
while (j < b.length) result.push(b[j++]);
return result;
};
const mergeUnique = (a, b) => {
return [...new Set([...a, ...b])];
};
const handleMerge = () => {
setMerged(mergeArrays(arr1, arr2));
};
return (
<div>
<h3>Merge Arrays</h3>
<p>Array 1: {arr1.join(', ')}</p>
<p>Array 2: {arr2.join(', ')}</p>
<button onClick={handleMerge}>Merge</button>
<p>Merged: {merged.join(', ')}</p>
<p>Sorted Merge: {mergeSorted([1,3,5,7], [2,4,6,8]).join(', ')}</p>
<p>Unique Merge: {mergeUnique([1,2,3], [3,4,5]).join(', ')}</p>
</div>
);
}Calculate sum using reduce or manual iteration.
- reduce:
arr.reduce((a, b) => a + b, 0) - Manual: Iterate and accumulate
- forEach:
arr.forEach(num => total += num) - Complexity: O(n) time
// Convert string to number in React
function StringToNumber() {
const [input, setInput] = useState('42');
const [result, setResult] = useState(null);
const stringToNumber = (s) => {
return Number(s);
};
const stringToInt = (s) => {
return parseInt(s, 10);
};
const stringToFloat = (s) => {
return parseFloat(s);
};
const stringToNumberSafe = (s) => {
const num = Number(s);
return isNaN(num) ? 0 : num;
};
const handleConvert = () => {
setResult({
number: stringToNumber(input),
int: stringToInt(input),
float: stringToFloat(input),
});
};
return (
<div>
<h3>String to Number</h3>
<input
value={input}
onChange={(e) => setInput(e.target.value)}
placeholder="Enter a number"
/>
<button onClick={handleConvert}>Convert</button>
{result && (
<div>
<p>Number: {result.number}</p>
<p>Int: {result.int}</p>
<p>Float: {result.float}</p>
<p>Safe: {stringToNumberSafe(input)}</p>
</div>
)}
</div>
);
}Calculate average using reduce or manual division.
- reduce:
arr.reduce((a, b) => a + b, 0) / arr.length - Manual: Sum then divide
- Empty array: Return 0
- Precision: Returns number
// Loop through dictionary in React
function DictionaryLoop() {
const [dict, setDict] = useState({
name: 'Alice',
age: 25,
city: 'NYC',
});
const [found, setFound] = useState('');
const loopDict = () => {
const entries = Object.entries(dict);
return entries.map(([key, value]) => (
<p key={key}>{key}: {value}</p>
));
};
const findKey = (key) => {
return dict[key] || null;
};
const handleFind = () => {
const value = findKey('name');
setFound(value || 'Not found');
};
return (
<div>
<h3>Dictionary Loop</h3>
{loopDict()}
<button onClick={handleFind}>Find 'name'</button>
<p>Found: {found}</p>
<p>Keys: {Object.keys(dict).join(', ')}</p>
<p>Values: {Object.values(dict).join(', ')}</p>
</div>
);
}Sort using sort with comparison function.
- Sort:
arr.slice().sort((a, b) => a - b) - In-place:
arr.sort((a, b) => a - b) - Strings:
sort((a, b) => a.localeCompare(b)) - Complexity: O(n log n)
// Delay function execution in React
function DelayExecution() {
const [message, setMessage] = useState('');
const delaySeconds = (seconds, callback) => {
return new Promise((resolve) => {
setTimeout(() => {
resolve(callback());
}, seconds * 1000);
});
};
const handleDelay = async () => {
setMessage('Starting delay...');
await delaySeconds(2, () => {
setMessage('After 2 seconds!');
});
};
const handleAsyncDelay = () => {
setMessage('Async delay started');
setTimeout(() => {
setMessage('Async delay completed');
}, 2000);
};
const handlePromiseDelay = () => {
setMessage('Promise delay started');
new Promise((resolve) => {
setTimeout(resolve, 2000);
}).then(() => {
setMessage('Promise delay completed');
});
};
return (
<div>
<h3>Delay Execution</h3>
<button onClick={handleDelay}>Delay 2s (Promise)</button>
<button onClick={handleAsyncDelay}>Delay 2s (setTimeout)</button>
<button onClick={handlePromiseDelay}>Delay 2s (Promise)</button>
<p>{message}</p>
</div>
);
}Sort descending by reversing comparison.
- Sort:
arr.slice().sort((a, b) => b - a) - In-place:
arr.sort((a, b) => b - a) - Strings:
sort((a, b) => b.localeCompare(a)) - Complexity: O(n log n)
// HTTP GET request in React
function HttpRequest() {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const fetchData = async () => {
setLoading(true);
try {
const response = await fetch('https://api.github.com');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const json = await response.json();
setData(json);
setError(null);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
};
const postData = async () => {
try {
const response = await fetch('https://httpbin.org/post', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ name: 'Alice', age: 25 }),
});
const json = await response.json();
console.log(json);
} catch (err) {
console.error(err);
}
};
return (
<div>
<h3>HTTP Request</h3>
<button onClick={fetchData}>Fetch Data</button>
<button onClick={postData}>POST Data</button>
{loading && <p>Loading...</p>}
{error && <p>Error: {error}</p>}
{data && (
<pre>{JSON.stringify(data, null, 2).slice(0, 500)}...</pre>
)}
</div>
);
}Flatten nested arrays using recursion or flat.
- Recursive: Check if element is array
- flat:
arr.flat(Infinity) - reduce:
reduce((acc, val) => acc.concat(Array.isArray(val) ? flatten(val) : val), []) - Complexity: O(n) time
// Create a promise-like task in React
function PromiseTask() {
const [result, setResult] = useState('');
const createPromise = (shouldResolve) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (shouldResolve) {
resolve('Success!');
} else {
reject('Failed!');
}
}, 1000);
});
};
const handlePromise = async () => {
try {
const result = await createPromise(true);
setResult(`Resolved: ${result}`);
} catch (error) {
setResult(`Rejected: ${error}`);
}
};
const handleFailedPromise = async () => {
try {
const result = await createPromise(false);
setResult(`Resolved: ${result}`);
} catch (error) {
setResult(`Rejected: ${error}`);
}
};
const chainPromises = async () => {
try {
const result1 = await createPromise(true);
setResult(`First: ${result1}`);
const result2 = await createPromise(true);
setResult(`Second: ${result2}`);
return [result1, result2];
} catch (error) {
setResult(`Error: ${error}`);
}
};
const promiseAll = async () => {
try {
const results = await Promise.all([
createPromise(true),
createPromise(true),
createPromise(true),
]);
setResult(`All: ${results.join(', ')}`);
} catch (error) {
setResult(`Error: ${error}`);
}
};
return (
<div>
<h3>Promise Task</h3>
<button onClick={handlePromise}>Resolve Promise</button>
<button onClick={handleFailedPromise}>Reject Promise</button>
<button onClick={chainPromises}>Chain Promises</button>
<button onClick={promiseAll}>Promise All</button>
<p>{result}</p>
</div>
);
}Split array into chunks using slice in loop.
- Loop: Iterate with step size
- slice:
arr.slice(i, i + size) - Edge case: Handle last chunk
- Complexity: O(n) time
// Factorial in React
function Factorial() {
const [n, setN] = useState(5);
const [result, setResult] = useState(null);
const factorialRecursive = (n) => {
if (n <= 1) return 1;
return n * factorialRecursive(n - 1);
};
const factorialIterative = (n) => {
let result = 1;
for (let i = 2; i <= n; i++) {
result *= i;
}
return result;
};
const factorialTail = (n, acc = 1) => {
if (n <= 1) return acc;
return factorialTail(n - 1, acc * n);
};
const handleCalculate = () => {
setResult({
recursive: factorialRecursive(n),
iterative: factorialIterative(n),
tail: factorialTail(n),
});
};
return (
<div>
<h3>Factorial</h3>
<input
type="number"
value={n}
onChange={(e) => setN(Number(e.target.value))}
min="0"
/>
<button onClick={handleCalculate}>Calculate</button>
{result && (
<div>
<p>Recursive: {result.recursive}</p>
<p>Iterative: {result.iterative}</p>
<p>Tail Recursive: {result.tail}</p>
</div>
)}
</div>
);
}Binary search using while loop or recursion.
- Iterative: While loop with left/right pointers
- Recursive: Recursive function call
- Requirement: Array must be sorted
- Complexity: O(log n) time
// Fibonacci in React
function Fibonacci() {
const [n, setN] = useState(10);
const [result, setResult] = useState(null);
const fibonacciRecursive = (n) => {
if (n <= 1) return n;
return fibonacciRecursive(n - 1) + fibonacciRecursive(n - 2);
};
const fibonacciIterative = (n) => {
if (n <= 1) return n;
let a = 0, b = 1;
for (let i = 2; i <= n; i++) {
[a, b] = [b, a + b];
}
return b;
};
const fibonacciMemoized = (n) => {
const cache = {};
const fib = (n) => {
if (n <= 1) return n;
if (cache[n]) return cache[n];
cache[n] = fib(n - 1) + fib(n - 2);
return cache[n];
};
return fib(n);
};
const handleCalculate = () => {
setResult({
recursive: fibonacciRecursive(n),
iterative: fibonacciIterative(n),
memoized: fibonacciMemoized(n),
});
};
return (
<div>
<h3>Fibonacci</h3>
<input
type="number"
value={n}
onChange={(e) => setN(Number(e.target.value))}
min="0"
/>
<button onClick={handleCalculate}>Calculate</button>
{result && (
<div>
<p>Recursive: {result.recursive}</p>
<p>Iterative: {result.iterative}</p>
<p>Memoized: {result.memoized}</p>
</div>
)}
</div>
);
}Quick sort using recursion and partitioning.
- Algorithm: Choose pivot, partition, recurse
- Time: O(n log n) average
- In-place: Implement for performance
- Pivot: First element or random
// FizzBuzz in React
function FizzBuzz() {
const [n, setN] = useState(15);
const [results, setResults] = useState([]);
const fizzbuzz = (n) => {
const result = [];
for (let i = 1; i <= n; i++) {
if (i % 15 === 0) {
result.push('FizzBuzz');
} else if (i % 3 === 0) {
result.push('Fizz');
} else if (i % 5 === 0) {
result.push('Buzz');
} else {
result.push(i);
}
}
return result;
};
const fizzbuzzMap = (n) => {
return Array.from({ length: n }, (_, i) => i + 1).map(i => {
if (i % 15 === 0) return 'FizzBuzz';
if (i % 3 === 0) return 'Fizz';
if (i % 5 === 0) return 'Buzz';
return i;
});
};
const handleGenerate = () => {
setResults(fizzbuzz(n));
};
return (
<div>
<h3>FizzBuzz</h3>
<input
type="number"
value={n}
onChange={(e) => setN(Number(e.target.value))}
min="1"
/>
<button onClick={handleGenerate}>Generate</button>
<div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px' }}>
{results.map((item, index) => (
<span
key={index}
style={{
padding: '4px 8px',
background: typeof item === 'string' ? '#e0e0e0' : '#f0f0f0',
borderRadius: '4px',
}}
>
{String(item)}
</span>
))}
</div>
</div>
);
}Merge sort using divide-and-conquer and merging.
- Algorithm: Divide, sort, merge
- Time: O(n log n)
- Stable: Maintains relative order
- Space: O(n) auxiliary space
// Find missing number in React
function FindMissing() {
const [array, setArray] = useState([1, 2, 4, 5, 6]);
const [missing, setMissing] = useState(null);
const findMissing = (arr) => {
const n = arr.length + 1;
const total = (n * (n + 1)) / 2;
const sum = arr.reduce((a, b) => a + b, 0);
return total - sum;
};
const findMissingXOR = (arr) => {
const n = arr.length + 1;
let xorAll = 0;
for (let i = 1; i <= n; i++) {
xorAll ^= i;
}
let xorArr = 0;
for (const val of arr) {
xorArr ^= val;
}
return xorAll ^ xorArr;
};
const handleFind = () => {
setMissing({
sum: findMissing(array),
xor: findMissingXOR(array),
});
};
return (
<div>
<h3>Find Missing Number</h3>
<p>Array: {array.join(', ')}</p>
<button onClick={handleFind}>Find Missing</button>
{missing && (
<div>
<p>Missing (sum): {missing.sum}</p>
<p>Missing (XOR): {missing.xor}</p>
</div>
)}
</div>
);
}Bubble sort with early termination optimization.
- Algorithm: Compare adjacent, swap
- Time: O(n²) worst case
- Optimization: Stop if no swaps
- In-place: Modifies original array
// Find duplicates in React
function FindDuplicates() {
const [array, setArray] = useState([1, 2, 3, 2, 4, 3, 5, 6, 5]);
const [duplicates, setDuplicates] = useState([]);
const findDuplicates = (arr) => {
const seen = new Set();
const dups = new Set();
for (const val of arr) {
if (seen.has(val)) {
dups.add(val);
} else {
seen.add(val);
}
}
return Array.from(dups);
};
const findDuplicatesCount = (arr) => {
const count = {};
for (const val of arr) {
count[val] = (count[val] || 0) + 1;
}
return Object.keys(count).filter(key => count[key] > 1).map(Number);
};
const findDuplicatesSort = (arr) => {
const sorted = [...arr].sort();
const dups = [];
for (let i = 1; i < sorted.length; i++) {
if (sorted[i] === sorted[i - 1] && !dups.includes(sorted[i])) {
dups.push(sorted[i]);
}
}
return dups;
};
const handleFind = () => {
setDuplicates(findDuplicates(array));
};
return (
<div>
<h3>Find Duplicates</h3>
<p>Array: {array.join(', ')}</p>
<button onClick={handleFind}>Find Duplicates</button>
<p>Duplicates: {duplicates.join(', ')}</p>
<p>Count method: {findDuplicatesCount(array).join(', ')}</p>
<p>Sort method: {findDuplicatesSort(array).join(', ')}</p>
</div>
);
}Find common elements using Set or filter.
- Set:
new Set(arr2)and filter - filter:
arr1.filter(item => arr2.includes(item)) - reduce: Accumulate common elements
- Complexity: O(n) time with Set
// Sum of array in React
function SumArray() {
const [array, setArray] = useState([1, 2, 3, 4, 5]);
const [sum, setSum] = useState(null);
const sumArray = (arr) => {
return arr.reduce((a, b) => a + b, 0);
};
const sumArrayManual = (arr) => {
let total = 0;
for (const val of arr) {
total += val;
}
return total;
};
const sumArrayRecursive = (arr) => {
if (arr.length === 0) return 0;
return arr[0] + sumArrayRecursive(arr.slice(1));
};
const handleSum = () => {
setSum({
reduce: sumArray(array),
manual: sumArrayManual(array),
recursive: sumArrayRecursive(array),
});
};
return (
<div>
<h3>Sum of Array</h3>
<p>Array: {array.join(', ')}</p>
<button onClick={handleSum}>Calculate Sum</button>
{sum && (
<div>
<p>Reduce: {sum.reduce}</p>
<p>Manual: {sum.manual}</p>
<p>Recursive: {sum.recursive}</p>
</div>
)}
</div>
);
}Combine arrays with unique elements using Set.
- Set:
[...new Set([...arr1, ...arr2])] - concat:
arr1.concat(arr2)then Set - Preserve order: Set preserves insertion order
- Complexity: O(n) time
// Average of array in React
function AverageArray() {
const [array, setArray] = useState([1, 2, 3, 4, 5]);
const [average, setAverage] = useState(null);
const averageArray = (arr) => {
if (arr.length === 0) return 0;
return arr.reduce((a, b) => a + b, 0) / arr.length;
};
const averageInteger = (arr) => {
if (arr.length === 0) return 0;
return Math.floor(arr.reduce((a, b) => a + b, 0) / arr.length);
};
const handleAverage = () => {
setAverage({
float: averageArray(array),
integer: averageInteger(array),
});
};
return (
<div>
<h3>Average of Array</h3>
<p>Array: {array.join(', ')}</p>
<button onClick={handleAverage}>Calculate Average</button>
{average && (
<div>
<p>Float: {average.float}</p>
<p>Integer: {average.integer}</p>
</div>
)}
</div>
);
}Find elements in first array not in second using Set.
- Set:
new Set(arr2)and filter - filter:
arr1.filter(item => !arr2.includes(item)) - Symmetric difference: Union of differences
- Complexity: O(n) time
// Sort array ascending in React
function SortAscending() {
const [array, setArray] = useState([5, 2, 8, 1, 9, 3]);
const [sorted, setSorted] = useState([]);
const sortAscending = (arr) => {
return [...arr].sort((a, b) => a - b);
};
const sortAscendingInPlace = (arr) => {
return arr.slice().sort((a, b) => a - b);
};
const handleSort = () => {
setSorted(sortAscending(array));
};
return (
<div>
<h3>Sort Ascending</h3>
<p>Original: {array.join(', ')}</p>
<button onClick={handleSort}>Sort</button>
<p>Sorted: {sorted.join(', ')}</p>
<p>In-place: {sortAscendingInPlace(array).join(', ')}</p>
</div>
);
}Group objects by property using reduce or for loop.
- reduce: Accumulate into object
- for loop: Manual grouping
- Key: Property value as key
- Complexity: O(n) time
// Sort array descending in React
function SortDescending() {
const [array, setArray] = useState([5, 2, 8, 1, 9, 3]);
const [sorted, setSorted] = useState([]);
const sortDescending = (arr) => {
return [...arr].sort((a, b) => b - a);
};
const sortDescendingInPlace = (arr) => {
return arr.slice().sort((a, b) => b - a);
};
const handleSort = () => {
setSorted(sortDescending(array));
};
return (
<div>
<h3>Sort Descending</h3>
<p>Original: {array.join(', ')}</p>
<button onClick={handleSort}>Sort</button>
<p>Sorted: {sorted.join(', ')}</p>
<p>In-place: {sortDescendingInPlace(array).join(', ')}</p>
</div>
);
}Deep clone using recursion or JSON methods.
- JSON:
JSON.parse(JSON.stringify(obj)) - Recursive: Copy nested structures
- Spread:
{...obj}(shallow) - Object.assign:
Object.assign({}, obj)(shallow)
// Flatten nested array in React
function FlattenArray() {
const [array, setArray] = useState([[1, 2], [3, 4, 5], [6], [7, 8, 9, 10]]);
const [flattened, setFlattened] = useState([]);
const flatten = (arr) => {
const result = [];
for (const item of arr) {
if (Array.isArray(item)) {
result.push(...flatten(item));
} else {
result.push(item);
}
}
return result;
};
const flattenIterative = (arr) => {
const result = [];
const stack = [...arr];
while (stack.length) {
const item = stack.pop();
if (Array.isArray(item)) {
stack.push(...item);
} else {
result.push(item);
}
}
return result.reverse();
};
const flattenOneLevel = (arr) => {
return arr.flat(1);
};
const handleFlatten = () => {
setFlattened(flatten(array));
};
return (
<div>
<h3>Flatten Array</h3>
<p>Original: {JSON.stringify(array)}</p>
<button onClick={handleFlatten}>Flatten</button>
<p>Flattened: {flattened.join(', ')}</p>
<p>Iterative: {flattenIterative(array).join(', ')}</p>
<p>One level: {flattenOneLevel(array).join(', ')}</p>
</div>
);
}Perform immutable updates using spread or Object.assign.
- Spread:
{...obj, [key]: value} - Object.assign:
Object.assign({}, obj, {[key]: value}) - Nested: Recursive spread updates
- Return: New immutable object
// Chunk array in React
function ChunkArray() {
const [array, setArray] = useState([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
const [chunks, setChunks] = useState([]);
const [size, setSize] = useState(3);
const chunkArray = (arr, size) => {
const result = [];
for (let i = 0; i < arr.length; i += size) {
result.push(arr.slice(i, i + size));
}
return result;
};
const chunkArrayReduce = (arr, size) => {
return arr.reduce((acc, item, index) => {
const chunkIndex = Math.floor(index / size);
if (!acc[chunkIndex]) {
acc[chunkIndex] = [];
}
acc[chunkIndex].push(item);
return acc;
}, []);
};
const handleChunk = () => {
setChunks(chunkArray(array, size));
};
return (
<div>
<h3>Chunk Array</h3>
<p>Array: {array.join(', ')}</p>
<input
type="number"
value={size}
onChange={(e) => setSize(Number(e.target.value))}
min="1"
/>
<button onClick={handleChunk}>Chunk</button>
<div>
{chunks.map((chunk, index) => (
<p key={index}>[{chunk.join(', ')}]</p>
))}
</div>
</div>
);
}Pipe composes functions from left to right.
- Implementation:
fns.reduce((acc, fn) => fn(acc), value) - Variadic: Accept multiple functions
- Return: Function that chains operations
- Direction: Left to right
// Binary search in React
function BinarySearch() {
const [array, setArray] = useState([1, 2, 3, 4, 5, 6, 7]);
const [target, setTarget] = useState(5);
const [result, setResult] = useState(null);
const binarySearch = (arr, target) => {
let left = 0;
let right = arr.length - 1;
while (left <= right) {
const mid = Math.floor((left + right) / 2);
if (arr[mid] === target) return mid;
if (arr[mid] < target) left = mid + 1;
else right = mid - 1;
}
return -1;
};
const binarySearchRecursive = (arr, target, left = 0, right = arr.length - 1) => {
if (left > right) return -1;
const mid = Math.floor((left + right) / 2);
if (arr[mid] === target) return mid;
if (arr[mid] < target) {
return binarySearchRecursive(arr, target, mid + 1, right);
}
return binarySearchRecursive(arr, target, left, mid - 1);
};
const handleSearch = () => {
setResult({
iterative: binarySearch(array, target),
recursive: binarySearchRecursive(array, target),
});
};
return (
<div>
<h3>Binary Search</h3>
<p>Array: {array.join(', ')}</p>
<input
type="number"
value={target}
onChange={(e) => setTarget(Number(e.target.value))}
/>
<button onClick={handleSearch}>Search</button>
{result && (
<div>
<p>Iterative: {result.iterative}</p>
<p>Recursive: {result.recursive}</p>
</div>
)}
</div>
);
}Compose functions from right to left.
- Implementation:
fns.reduceRight((acc, fn) => fn(acc), value) - Variadic: Accept multiple functions
- Return: Function that chains operations
- Direction: Right to left
// Quick sort in React
function QuickSort() {
const [array, setArray] = useState([5, 3, 8, 4, 2, 7, 1, 6]);
const [sorted, setSorted] = useState([]);
const quickSort = (arr) => {
if (arr.length <= 1) return arr;
const pivot = arr[0];
const left = arr.filter(x => x < pivot);
const right = arr.filter(x => x > pivot);
return [...quickSort(left), pivot, ...quickSort(right)];
};
const quickSortInPlace = (arr, low = 0, high = arr.length - 1) => {
if (low < high) {
const pi = partition(arr, low, high);
quickSortInPlace(arr, low, pi - 1);
quickSortInPlace(arr, pi + 1, high);
}
return arr;
};
const partition = (arr, low, high) => {
const pivot = arr[high];
let i = low - 1;
for (let j = low; j < high; j++) {
if (arr[j] <= pivot) {
i++;
[arr[i], arr[j]] = [arr[j], arr[i]];
}
}
[arr[i + 1], arr[high]] = [arr[high], arr[i + 1]];
return i + 1;
};
const handleSort = () => {
setSorted(quickSort([...array]));
};
return (
<div>
<h3>Quick Sort</h3>
<p>Original: {array.join(', ')}</p>
<button onClick={handleSort}>Sort</button>
<p>Sorted: {sorted.join(', ')}</p>
<p>In-place: {quickSortInPlace([...array]).join(', ')}</p>
</div>
);
}Cache function results based on arguments using object.
- Cache:
orMap - Key:
JSON.stringify(args) - Return: Cached or computed result
- Trade-off: Memory for speed
// Merge sort in React
function MergeSort() {
const [array, setArray] = useState([5, 3, 8, 4, 2, 7, 1, 6]);
const [sorted, setSorted] = useState([]);
const mergeSort = (arr) => {
if (arr.length <= 1) return arr;
const mid = Math.floor(arr.length / 2);
const left = mergeSort(arr.slice(0, mid));
const right = mergeSort(arr.slice(mid));
return merge(left, right);
};
const merge = (left, right) => {
const result = [];
let i = 0, j = 0;
while (i < left.length && j < right.length) {
if (left[i] <= right[j]) {
result.push(left[i++]);
} else {
result.push(right[j++]);
}
}
return [...result, ...left.slice(i), ...right.slice(j)];
};
const handleSort = () => {
setSorted(mergeSort([...array]));
};
return (
<div>
<h3>Merge Sort</h3>
<p>Original: {array.join(', ')}</p>
<button onClick={handleSort}>Sort</button>
<p>Sorted: {sorted.join(', ')}</p>
</div>
);
}Ensure a function is called only once using closure.
- Closure:
let called = false - Result: Cache the result
- Return: Function with guard
- Use case: Initialization
// Bubble sort in React
function BubbleSort() {
const [array, setArray] = useState([5, 3, 8, 4, 2, 7, 1, 6]);
const [sorted, setSorted] = useState([]);
const [steps, setSteps] = useState([]);
const bubbleSort = (arr) => {
const result = [...arr];
const n = result.length;
const steps = [];
for (let i = 0; i < n - 1; i++) {
for (let j = 0; j < n - i - 1; j++) {
if (result[j] > result[j + 1]) {
[result[j], result[j + 1]] = [result[j + 1], result[j]];
steps.push([...result]);
}
}
}
return { sorted: result, steps };
};
const bubbleSortOptimized = (arr) => {
const result = [...arr];
const n = result.length;
for (let i = 0; i < n - 1; i++) {
let swapped = false;
for (let j = 0; j < n - i - 1; j++) {
if (result[j] > result[j + 1]) {
[result[j], result[j + 1]] = [result[j + 1], result[j]];
swapped = true;
}
}
if (!swapped) break;
}
return result;
};
const handleSort = () => {
const result = bubbleSort(array);
setSorted(result.sorted);
setSteps(result.steps);
};
return (
<div>
<h3>Bubble Sort</h3>
<p>Original: {array.join(', ')}</p>
<button onClick={handleSort}>Sort</button>
<p>Sorted: {sorted.join(', ')}</p>
<p>Optimized: {bubbleSortOptimized(array).join(', ')}</p>
<div>
<h4>Steps:</h4>
{steps.slice(0, 10).map((step, i) => (
<p key={i}>[{step.join(', ')}]</p>
))}
</div>
</div>
);
}Debounce with leading edge using timer and timestamp.
- Timer:
setTimeoutfor delayed execution - Leading edge: Execute immediately
- Cooldown: Wait before next execution
- Use case: Search input, API calls
// Intersection of arrays in React
function IntersectionArrays() {
const [arr1, setArr1] = useState(['apple', 'banana', 'orange', 'grape', 'kiwi']);
const [arr2, setArr2] = useState(['banana', 'kiwi', 'mango', 'grape']);
const [intersection, setIntersection] = useState([]);
const findIntersection = (a, b) => {
return a.filter(x => b.includes(x));
};
const findIntersectionSet = (a, b) => {
const setB = new Set(b);
return [...new Set(a.filter(x => setB.has(x)))];
};
const findIntersectionMultiple = (...arrays) => {
if (arrays.length === 0) return [];
return arrays.reduce((acc, arr) =>
acc.filter(x => arr.includes(x))
);
};
const handleIntersect = () => {
setIntersection(findIntersection(arr1, arr2));
};
return (
<div>
<h3>Intersection</h3>
<p>Array 1: {arr1.join(', ')}</p>
<p>Array 2: {arr2.join(', ')}</p>
<button onClick={handleIntersect}>Intersect</button>
<p>Intersection: {intersection.join(', ')}</p>
<p>Set method: {findIntersectionSet(arr1, arr2).join(', ')}</p>
</div>
);
}Throttle with leading edge using timestamp tracking.
- Timestamp: Track last execution time
- Leading edge: Execute if enough time passed
- Rate limiting: At most once per period
- Use case: Scroll events, resize
// Union of arrays in React
function UnionArrays() {
const [arr1, setArr1] = useState(['apple', 'banana', 'orange']);
const [arr2, setArr2] = useState(['orange', 'grape', 'kiwi']);
const [union, setUnion] = useState([]);
const findUnion = (a, b) => {
return [...new Set([...a, ...b])];
};
const findUnionManual = (a, b) => {
const result = [...a];
for (const val of b) {
if (!result.includes(val)) {
result.push(val);
}
}
return result;
};
const findUnionMultiple = (...arrays) => {
return [...new Set(arrays.flat())];
};
const handleUnion = () => {
setUnion(findUnion(arr1, arr2));
};
return (
<div>
<h3>Union</h3>
<p>Array 1: {arr1.join(', ')}</p>
<p>Array 2: {arr2.join(', ')}</p>
<button onClick={handleUnion}>Union</button>
<p>Union: {union.join(', ')}</p>
<p>Manual: {findUnionManual(arr1, arr2).join(', ')}</p>
</div>
);
}Deep equality comparison using recursion for nested structures.
- Recursive: Compare nested structures
- Base cases: Primitive values
- Arrays: Compare elements recursively
- Objects: Compare key-value pairs
// Difference of arrays in React
function DifferenceArrays() {
const [arr1, setArr1] = useState(['apple', 'banana', 'orange', 'grape']);
const [arr2, setArr2] = useState(['banana', 'kiwi', 'grape']);
const [diff, setDiff] = useState([]);
const findDifference = (a, b) => {
return a.filter(x => !b.includes(x));
};
const findSymmetricDifference = (a, b) => {
const diff1 = a.filter(x => !b.includes(x));
const diff2 = b.filter(x => !a.includes(x));
return [...diff1, ...diff2];
};
const findDifferenceMultiple = (...arrays) => {
if (arrays.length === 0) return [];
return arrays.reduce((acc, arr) =>
acc.filter(x => !arr.includes(x))
);
};
const handleDifference = () => {
setDiff(findDifference(arr1, arr2));
};
return (
<div>
<h3>Difference</h3>
<p>Array 1: {arr1.join(', ')}</p>
<p>Array 2: {arr2.join(', ')}</p>
<button onClick={handleDifference}>Difference</button>
<p>Difference: {diff.join(', ')}</p>
<p>Symmetric: {findSymmetricDifference(arr1, arr2).join(', ')}</p>
</div>
);
}Observable pattern with subscribers and notifications.
- Observable: Maintains subscribers
- Subscribe: Add callback
- Notify: Call all subscribers
- Unsubscribe: Remove callback
// Group by property in React
function GroupByProperty() {
const [people, setPeople] = useState([
{ name: 'Alice', age: 25, city: 'NYC' },
{ name: 'Bob', age: 30, city: 'LA' },
{ name: 'Charlie', age: 25, city: 'NYC' },
{ name: 'David', age: 35, city: 'Chicago' },
{ name: 'Eve', age: 30, city: 'LA' },
]);
const [grouped, setGrouped] = useState({});
const groupBy = (arr, key) => {
return arr.reduce((acc, item) => {
const groupKey = item[key];
if (!acc[groupKey]) {
acc[groupKey] = [];
}
acc[groupKey].push(item);
return acc;
}, {});
};
const groupAndCount = (arr, key) => {
return arr.reduce((acc, item) => {
const groupKey = item[key];
acc[groupKey] = (acc[groupKey] || 0) + 1;
return acc;
}, {});
};
const groupAndSum = (arr, groupKey, sumKey) => {
return arr.reduce((acc, item) => {
const key = item[groupKey];
acc[key] = (acc[key] || 0) + item[sumKey];
return acc;
}, {});
};
const handleGroup = () => {
setGrouped(groupBy(people, 'age'));
};
const handleGroupCity = () => {
setGrouped(groupBy(people, 'city'));
};
return (
<div>
<h3>Group By</h3>
<button onClick={handleGroup}>Group by Age</button>
<button onClick={handleGroupCity}>Group by City</button>
<div>
{Object.entries(grouped).map(([key, items]) => (
<div key={key}>
<h4>{key}:</h4>
<ul>
{items.map((item, i) => (
<li key={i}>{item.name} ({item.age})</li>
))}
</ul>
</div>
))}
</div>
<p>Count by age: {JSON.stringify(groupAndCount(people, 'age'))}</p>
</div>
);
}Singleton pattern using closure or class with static instance.
- Closure: IIFE with private instance
- Class: Static getInstance method
- Lazy initialization: Create on first access
- Global access: Through shared instance
// Deep clone object in React
function DeepClone() {
const [original, setOriginal] = useState({
name: 'Alice',
address: {
street: '123 Main St',
city: 'NYC',
},
hobbies: ['reading', 'coding'],
});
const [cloned, setCloned] = useState(null);
const deepClone = (obj) => {
if (obj === null || typeof obj !== 'object') return obj;
if (Array.isArray(obj)) {
return obj.map(item => deepClone(item));
}
const result = {};
for (const key in obj) {
result[key] = deepClone(obj[key]);
}
return result;
};
const handleClone = () => {
setCloned(deepClone(original));
};
const modifyClone = () => {
if (cloned) {
cloned.address.street = '456 Oak St';
cloned.hobbies.push('gaming');
setCloned({ ...cloned });
}
};
return (
<div>
<h3>Deep Clone</h3>
<button onClick={handleClone}>Clone</button>
<button onClick={modifyClone}>Modify Clone</button>
<div>
<h4>Original:</h4>
<pre>{JSON.stringify(original, null, 2)}</pre>
</div>
{cloned && (
<div>
<h4>Cloned:</h4>
<pre>{JSON.stringify(cloned, null, 2)}</pre>
</div>
)}
</div>
);
}Factory pattern using functions that create objects.
- Factory function: Creates objects
- Type parameter: Determines which class
- Return: Instance of requested type
- Benefits: Decouples creation logic
// Immutable update in React
function ImmutableUpdate() {
const [state, setState] = useState({
user: {
name: 'Alice',
age: 25,
address: {
city: 'NYC',
zip: '10001',
},
},
});
const [newState, setNewState] = useState(null);
const updateImmutable = (obj, path, value) => {
const parts = path.split('.');
if (parts.length === 1) {
return { ...obj, [parts[0]]: value };
}
const first = parts[0];
const rest = parts.slice(1).join('.');
return {
...obj,
[first]: updateImmutable(obj[first] || {}, rest, value),
};
};
const handleUpdate = () => {
const updated = updateImmutable(state, 'user.age', 26);
setNewState(updated);
};
const handleNestedUpdate = () => {
const updated = updateImmutable(state, 'user.address.city', 'LA');
setNewState(updated);
};
return (
<div>
<h3>Immutable Update</h3>
<button onClick={handleUpdate}>Update Age</button>
<button onClick={handleNestedUpdate}>Update City</button>
<div>
<h4>Original:</h4>
<pre>{JSON.stringify(state, null, 2)}</pre>
</div>
{newState && (
<div>
<h4>Updated:</h4>
<pre>{JSON.stringify(newState, null, 2)}</pre>
</div>
)}
</div>
);
}Strategy pattern using functions or objects with algorithms.
- Strategy functions: Different algorithms
- Context: Uses strategy
- Runtime switching: Change at runtime
- Benefits: Encapsulate algorithms
// Pipe function in React
function PipeFunction() {
const [value, setValue] = useState(5);
const [result, setResult] = useState(null);
const double = (x) => x * 2;
const addTen = (x) => x + 10;
const square = (x) => x * x;
const pipe = (...fns) => {
return (x) => fns.reduce((acc, fn) => fn(acc), x);
};
const compose = (...fns) => {
return (x) => fns.reduceRight((acc, fn) => fn(acc), x);
};
const process = pipe(double, addTen, square);
const processCompose = compose(square, addTen, double);
const handlePipe = () => {
setResult({
pipe: process(value),
compose: processCompose(value),
});
};
return (
<div>
<h3>Pipe Function</h3>
<input
type="number"
value={value}
onChange={(e) => setValue(Number(e.target.value))}
/>
<button onClick={handlePipe}>Process</button>
{result && (
<div>
<p>Pipe: {result.pipe}</p>
<p>Compose: {result.compose}</p>
</div>
)}
</div>
);
}Observer pattern with subject and observers.
- Subject: Maintains observers
- Observer: Defines update method
- Attach/Detach: Add/remove observers
- Notify: Call update on all observers
// Compose function in React
function ComposeFunction() {
const [value, setValue] = useState(5);
const [result, setResult] = useState(null);
const double = (x) => x * 2;
const addTen = (x) => x + 10;
const square = (x) => x * x;
const compose = (...fns) => {
return (x) => fns.reduceRight((acc, fn) => fn(acc), x);
};
const composeAlt = (...fns) => {
return fns.reduce((f, g) => (x) => f(g(x)));
};
const process = compose(square, addTen, double);
const processAlt = composeAlt(square, addTen, double);
const handleCompose = () => {
setResult({
compose: process(value),
composeAlt: processAlt(value),
});
};
return (
<div>
<h3>Compose Function</h3>
<input
type="number"
value={value}
onChange={(e) => setValue(Number(e.target.value))}
/>
<button onClick={handleCompose}>Compose</button>
{result && (
<div>
<p>Compose: {result.compose}</p>
<p>Compose Alt: {result.composeAlt}</p>
</div>
)}
</div>
);
}Decorator pattern using wrapper functions or classes.
- Component: Base object
- Decorator: Wraps component
- Chaining: Multiple decorators
- Benefits: Add behavior dynamically
// Memoization in React
function MemoizationExample() {
const [n, setN] = useState(35);
const [result, setResult] = useState(null);
const [time, setTime] = useState(null);
const memoize = (fn) => {
const cache = {};
return (arg) => {
if (cache[arg] !== undefined) {
return cache[arg];
}
const result = fn(arg);
cache[arg] = result;
return result;
};
};
const fib = (n) => {
if (n <= 1) return n;
return fib(n - 1) + fib(n - 2);
};
const fibMemoized = memoize((n) => {
if (n <= 1) return n;
return fibMemoized(n - 1) + fibMemoized(n - 2);
});
const handleCalculate = () => {
const start = performance.now();
const result = fibMemoized(n);
const end = performance.now();
setResult(result);
setTime(end - start);
};
const handleCalculateWithoutMemo = () => {
const start = performance.now();
const result = fib(n);
const end = performance.now();
setResult(result);
setTime(end - start);
};
return (
<div>
<h3>Memoization</h3>
<input
type="number"
value={n}
onChange={(e) => setN(Number(e.target.value))}
min="0"
/>
<button onClick={handleCalculate}>With Memoization</button>
<button onClick={handleCalculateWithoutMemo}>Without Memoization</button>
{result !== null && (
<div>
<p>Result: {result}</p>
<p>Time: {time?.toFixed(2)}ms</p>
</div>
)}
</div>
);
}Command pattern with execute and undo methods.
- Command: Execute and undo methods
- Receiver: Performs actual work
- Invoker: Executes commands
- Undo/Redo: Command history
// Once function in React
function OnceFunction() {
const [result, setResult] = useState('');
const once = (fn) => {
let called = false;
let result = null;
return (...args) => {
if (!called) {
called = true;
result = fn(...args);
}
return result;
};
};
const onceWithReset = (fn) => {
let called = false;
let result = null;
const reset = () => {
called = false;
result = null;
};
const fnOnce = (...args) => {
if (!called) {
called = true;
result = fn(...args);
}
return result;
};
return { fn: fnOnce, reset };
};
const initialize = once((value) => {
console.log('Initialized with', value);
return value * 2;
});
const { fn, reset } = onceWithReset((value) => {
console.log('Initialized with', value);
return value * 2;
});
const handleOnce = () => {
const r1 = initialize(10);
const r2 = initialize(20);
setResult(`First: ${r1}, Second: ${r2}`);
};
const handleOnceReset = () => {
const r1 = fn(10);
reset();
const r2 = fn(20);
setResult(`First: ${r1}, After reset: ${r2}`);
};
return (
<div>
<h3>Once Function</h3>
<button onClick={handleOnce}>Once</button>
<button onClick={handleOnceReset}>Once with Reset</button>
<p>{result}</p>
</div>
);
}Memento pattern for state capture and restoration.
- Originator: Creates and restores mementos
- Memento: Stores state
- Caretaker: Manages mementos
- Undo/Redo: State history
// Debounce with leading edge in React
function DebounceExample() {
const [value, setValue] = useState('');
const [debouncedValue, setDebouncedValue] = useState('');
const debounceLeading = (fn, delay) => {
let lastCall = 0;
let timeoutId = null;
return (...args) => {
const now = Date.now();
if (now - lastCall >= delay) {
lastCall = now;
return fn(...args);
}
if (timeoutId === null) {
timeoutId = setTimeout(() => {
timeoutId = null;
lastCall = Date.now();
fn(...args);
}, delay - (now - lastCall));
}
};
};
const debounceSimple = (fn, delay) => {
let lastCall = 0;
return (...args) => {
const now = Date.now();
if (now - lastCall >= delay) {
lastCall = now;
return fn(...args);
}
return null;
};
};
const handleSearch = debounceLeading((val) => {
setDebouncedValue(val);
console.log('Searching:', val);
}, 500);
const handleChange = (e) => {
const val = e.target.value;
setValue(val);
handleSearch(val);
};
return (
<div>
<h3>Debounce</h3>
<input
type="text"
value={value}
onChange={handleChange}
placeholder="Type something..."
/>
<p>Value: {value}</p>
<p>Debounced: {debouncedValue}</p>
</div>
);
}Mediator pattern for centralized communication.
- Mediator: Encapsulates communication
- Colleague: Communicates through mediator
- Benefits: Loose coupling
- Use case: Chat systems
// Throttle with leading edge in React
function ThrottleExample() {
const [value, setValue] = useState('');
const [throttledValue, setThrottledValue] = useState('');
const throttleLeading = (fn, delay) => {
let lastCall = 0;
return (...args) => {
const now = Date.now();
if (now - lastCall >= delay) {
lastCall = now;
return fn(...args);
}
return null;
};
};
const throttleWithTrailing = (fn, delay) => {
let lastCall = 0;
let pending = null;
let timer = null;
return (...args) => {
const now = Date.now();
if (now - lastCall >= delay) {
lastCall = now;
return fn(...args);
}
pending = args;
if (timer === null) {
timer = setTimeout(() => {
timer = null;
lastCall = Date.now();
if (pending) {
fn(...pending);
pending = null;
}
}, delay - (now - lastCall));
}
};
};
const handleThrottle = throttleLeading((val) => {
setThrottledValue(val);
console.log('Throttled:', val);
}, 1000);
const handleChange = (e) => {
const val = e.target.value;
setValue(val);
handleThrottle(val);
};
return (
<div>
<h3>Throttle</h3>
<input
type="text"
value={value}
onChange={handleChange}
placeholder="Type something..."
/>
<p>Value: {value}</p>
<p>Throttled: {throttledValue}</p>
</div>
);
}Chain of Responsibility for processing requests sequentially.
- Handler: Processes or forwards
- Chain: Linked list of handlers
- Benefits: Decoupling
- Use case: Logging, authentication
// Deep equal in React
function DeepEqual() {
const [obj1, setObj1] = useState({ a: 1, b: { c: 2 } });
const [obj2, setObj2] = useState({ a: 1, b: { c: 2 } });
const [isEqual, setIsEqual] = useState(false);
const deepEqual = (a, b) => {
if (a === b) return true;
if (typeof a !== 'object' || typeof b !== 'object') return false;
if (a === null || b === null) return false;
if (Array.isArray(a) !== Array.isArray(b)) return false;
const keysA = Object.keys(a);
const keysB = Object.keys(b);
if (keysA.length !== keysB.length) return false;
for (const key of keysA) {
if (!keysB.includes(key)) return false;
if (!deepEqual(a[key], b[key])) return false;
}
return true;
};
const handleCompare = () => {
setIsEqual(deepEqual(obj1, obj2));
};
const modifyObj = () => {
setObj2({ ...obj2, b: { c: 3 } });
};
return (
<div>
<h3>Deep Equal</h3>
<button onClick={handleCompare}>Compare</button>
<button onClick={modifyObj}>Modify Object 2</button>
<div>
<h4>Object 1:</h4>
<pre>{JSON.stringify(obj1, null, 2)}</pre>
</div>
<div>
<h4>Object 2:</h4>
<pre>{JSON.stringify(obj2, null, 2)}</pre>
</div>
<p>Equal: {String(isEqual)}</p>
</div>
);
}State pattern for changing behavior with state.
- Context: Maintains state
- State: Defines behavior
- Transitions: Change between states
- Benefits: Clean state management
// Observable pattern in React
function ObservableExample() {
const [messages, setMessages] = useState([]);
class Observable {
constructor() {
this.subscribers = [];
}
subscribe(callback) {
this.subscribers.push(callback);
return () => {
this.subscribers = this.subscribers.filter(cb => cb !== callback);
};
}
notify(data) {
this.subscribers.forEach(callback => callback(data));
}
}
const observable = new Observable();
const addMessage = (msg) => {
setMessages(prev => [...prev, msg]);
};
useEffect(() => {
const unsubscribe = observable.subscribe((data) => {
addMessage(`Received: ${data}`);
});
return () => {
unsubscribe();
};
}, []);
const sendMessage = () => {
const msg = `Message at ${new Date().toLocaleTimeString()}`;
observable.notify(msg);
};
return (
<div>
<h3>Observable Pattern</h3>
<button onClick={sendMessage}>Send Message</button>
<div>
<h4>Messages:</h4>
<ul>
{messages.map((msg, i) => (
<li key={i}>{msg}</li>
))}
</ul>
</div>
</div>
);
}Proxy pattern for controlling access to objects.
- Subject: Real object
- Proxy: Controls access
- Lazy loading: Create on demand
- Benefits: Access control, logging
// Singleton pattern in React
function SingletonExample() {
const [value, setValue] = useState('');
class Singleton {
constructor() {
if (!Singleton.instance) {
Singleton.instance = this;
this.data = {};
}
return Singleton.instance;
}
set(key, value) {
this.data[key] = value;
}
get(key) {
return this.data[key] || null;
}
}
const singleton1 = new Singleton();
const singleton2 = new Singleton();
const handleSet = () => {
singleton1.set('key', 'value');
setValue(singleton2.get('key'));
};
const handleGet = () => {
setValue(singleton1.get('key') || 'Not found');
};
return (
<div>
<h3>Singleton Pattern</h3>
<button onClick={handleSet}>Set Value (via Singleton 1)</button>
<button onClick={handleGet}>Get Value (via Singleton 1)</button>
<p>Value: {value}</p>
<p>Singleton 1 === Singleton 2: {String(singleton1 === singleton2)}</p>
</div>
);
}Flyweight pattern for sharing objects to save memory.
- Flyweight: Shared object
- Factory: Manages flyweights
- Benefits: Memory optimization
- Use case: Character rendering
// Factory pattern in React
function FactoryExample() {
const [users, setUsers] = useState([]);
class User {
constructor(name, type) {
this.name = name;
this.type = type;
}
}
class Admin extends User {
constructor(name) {
super(name, 'admin');
}
}
class Guest extends User {
constructor(name) {
super(name, 'guest');
}
}
class RegularUser extends User {
constructor(name) {
super(name, 'regular');
}
}
class UserFactory {
static create(type, name) {
switch (type) {
case 'admin':
return new Admin(name);
case 'guest':
return new Guest(name);
default:
return new RegularUser(name);
}
}
static createAdmin(name) {
return new Admin(name);
}
static createGuest(name) {
return new Guest(name);
}
static createRegular(name) {
return new RegularUser(name);
}
}
const addUser = (type, name) => {
const user = UserFactory.create(type, name);
setUsers(prev => [...prev, user]);
};
return (
<div>
<h3>Factory Pattern</h3>
<button onClick={() => addUser('admin', 'Alice')}>Add Admin</button>
<button onClick={() => addUser('guest', 'Bob')}>Add Guest</button>
<button onClick={() => addUser('regular', 'Charlie')}>Add Regular</button>
<div>
<h4>Users:</h4>
<ul>
{users.map((user, i) => (
<li key={i}>{user.name} ({user.type})</li>
))}
</ul>
</div>
</div>
);
}Bridge pattern for separating abstraction from implementation.
- Abstraction: High-level interface
- Implementation: Low-level operations
- Benefits: Separation of concerns
- Use case: Cross-platform
// Strategy pattern in React
function StrategyExample() {
const [paymentMethod, setPaymentMethod] = useState('credit');
const [amount, setAmount] = useState(100);
const payWithCreditCard = (amount) => {
return `Paid ${amount} with Credit Card`;
};
const payWithPayPal = (amount) => {
return `Paid ${amount} with PayPal`;
};
const payWithCrypto = (amount) => {
return `Paid ${amount} with Crypto`;
};
const paymentStrategies = {
credit: payWithCreditCard,
paypal: payWithPayPal,
crypto: payWithCrypto,
};
const [result, setResult] = useState('');
const handlePayment = () => {
const strategy = paymentStrategies[paymentMethod];
const result = strategy(amount);
setResult(result);
};
return (
<div>
<h3>Strategy Pattern</h3>
<select
value={paymentMethod}
onChange={(e) => setPaymentMethod(e.target.value)}
>
<option value="credit">Credit Card</option>
<option value="paypal">PayPal</option>
<option value="crypto">Crypto</option>
</select>
<input
type="number"
value={amount}
onChange={(e) => setAmount(Number(e.target.value))}
/>
<button onClick={handlePayment}>Pay</button>
<p>{result}</p>
</div>
);
}Adapter pattern for converting interfaces.
- Target: Expected interface
- Adaptee: Existing interface
- Adapter: Bridges interfaces
- Benefits: Reusability
// Observer pattern in React
function ObserverExample() {
const [state, setState] = useState('Initial state');
const [observers, setObservers] = useState([]);
class Subject {
constructor() {
this.observers = [];
}
attach(observer) {
this.observers.push(observer);
return () => this.detach(observer);
}
detach(observer) {
this.observers = this.observers.filter(obs => obs !== observer);
}
notify(data) {
this.observers.forEach(observer => observer(data));
}
}
const subject = new Subject();
const addObserver = () => {
const id = observers.length + 1;
const observer = (data) => {
setObservers(prev => {
const updated = [...prev];
const idx = updated.findIndex(o => o.id === id);
if (idx !== -1) {
updated[idx] = { ...updated[idx], lastData: data };
}
return updated;
});
};
setObservers(prev => [...prev, { id, name: `Observer ${id}`, lastData: null }]);
subject.attach(observer);
};
const notifyAll = () => {
subject.notify(`State: ${state}`);
};
const updateState = () => {
setState(`State at ${new Date().toLocaleTimeString()}`);
};
return (
<div>
<h3>Observer Pattern</h3>
<button onClick={addObserver}>Add Observer</button>
<button onClick={updateState}>Update State</button>
<button onClick={notifyAll}>Notify All</button>
<p>Current State: {state}</p>
<div>
<h4>Observers:</h4>
<ul>
{observers.map(obs => (
<li key={obs.id}>
{obs.name}: {obs.lastData || 'No data yet'}
</li>
))}
</ul>
</div>
</div>
);
}Facade pattern for simplifying complex subsystems.
- Facade: Simplified interface
- Subsystem: Complex components
- Benefits: Simplified interface
- Use case: Library APIs
// Decorator pattern in React
function DecoratorExample() {
const [coffee, setCoffee] = useState({
cost: 5.0,
description: 'Coffee',
});
const milkDecorator = (coffee) => ({
cost: coffee.cost + 2.0,
description: coffee.description + ', Milk',
});
const sugarDecorator = (coffee) => ({
cost: coffee.cost + 1.0,
description: coffee.description + ', Sugar',
});
const caramelDecorator = (coffee) => ({
cost: coffee.cost + 2.5,
description: coffee.description + ', Caramel',
});
const whippedCreamDecorator = (coffee) => ({
cost: coffee.cost + 1.5,
description: coffee.description + ', Whipped Cream',
});
const applyDecorators = (base, decorators) => {
return decorators.reduce((acc, dec) => dec(acc), base);
};
const [decorated, setDecorated] = useState(null);
const handleAddMilk = () => {
setCoffee(milkDecorator(coffee));
};
const handleAddSugar = () => {
setCoffee(sugarDecorator(coffee));
};
const handleFullDecorated = () => {
const decorators = [milkDecorator, sugarDecorator, caramelDecorator, whippedCreamDecorator];
const result = applyDecorators({ cost: 5.0, description: 'Coffee' }, decorators);
setDecorated(result);
};
return (
<div>
<h3>Decorator Pattern</h3>
<div>
<h4>Current Coffee:</h4>
<p>{coffee.description} (${(coffee.cost).toFixed(2)})</p>
</div>
<button onClick={handleAddMilk}>Add Milk</button>
<button onClick={handleAddSugar}>Add Sugar</button>
<button onClick={handleFullDecorated}>Full Decorated</button>
{decorated && (
<div>
<h4>Fully Decorated:</h4>
<p>{decorated.description} (${(decorated.cost).toFixed(2)})</p>
</div>
)}
</div>
);
}Composite pattern for tree structures.
- Component: Interface for all
- Leaf: Individual object
- Composite: Container
- Benefits: Uniform interface
// Command pattern in React
function CommandExample() {
const [counter, setCounter] = useState(0);
const [history, setHistory] = useState([]);
const [currentIndex, setCurrentIndex] = useState(-1);
class Command {
execute() {}
undo() {}
redo() {}
}
class AddCommand extends Command {
constructor(value) {
super();
this.value = value;
}
execute() {
setCounter(prev => prev + this.value);
return this.value;
}
undo() {
setCounter(prev => prev - this.value);
return -this.value;
}
redo() {
return this.execute();
}
}
class SubtractCommand extends Command {
constructor(value) {
super();
this.value = value;
}
execute() {
setCounter(prev => prev - this.value);
return -this.value;
}
undo() {
setCounter(prev => prev + this.value);
return this.value;
}
redo() {
return this.execute();
}
}
const executeCommand = (command) => {
const result = command.execute();
setHistory(prev => [...prev.slice(0, currentIndex + 1), { command, result }]);
setCurrentIndex(prev => prev + 1);
};
const undo = () => {
if (currentIndex >= 0) {
const entry = history[currentIndex];
entry.command.undo();
setCurrentIndex(prev => prev - 1);
}
};
const redo = () => {
if (currentIndex < history.length - 1) {
const entry = history[currentIndex + 1];
entry.command.redo();
setCurrentIndex(prev => prev + 1);
}
};
return (
<div>
<h3>Command Pattern</h3>
<p>Counter: {counter}</p>
<button onClick={() => executeCommand(new AddCommand(5))}>Add 5</button>
<button onClick={() => executeCommand(new SubtractCommand(3))}>Subtract 3</button>
<button onClick={undo}>Undo</button>
<button onClick={redo}>Redo</button>
<p>History: {currentIndex + 1} / {history.length}</p>
</div>
);
}Visitor pattern for adding operations without modifying elements.
- Visitor: Defines operations
- Element: Accepts visitors
- Benefits: Adding operations without modifying
- Use case: Compilers, AST
// Memento pattern in React
function MementoExample() {
const [state, setState] = useState({ value: 0 });
const [mementos, setMementos] = useState([]);
const [currentIndex, setCurrentIndex] = useState(-1);
class Memento {
constructor(state) {
this.state = state;
}
getState() {
return this.state;
}
}
const saveState = () => {
const memento = new Memento({ ...state });
setMementos(prev => [...prev.slice(0, currentIndex + 1), memento]);
setCurrentIndex(prev => prev + 1);
};
const undo = () => {
if (currentIndex > 0) {
const prevMemento = mementos[currentIndex - 1];
setState(prevMemento.getState());
setCurrentIndex(prev => prev - 1);
}
};
const redo = () => {
if (currentIndex < mementos.length - 1) {
const nextMemento = mementos[currentIndex + 1];
setState(nextMemento.getState());
setCurrentIndex(prev => prev + 1);
}
};
const updateValue = (newValue) => {
setState({ value: newValue });
};
return (
<div>
<h3>Memento Pattern</h3>
<p>Value: {state.value}</p>
<input
type="number"
value={state.value}
onChange={(e) => updateValue(Number(e.target.value))}
/>
<button onClick={saveState}>Save</button>
<button onClick={undo}>Undo</button>
<button onClick={redo}>Redo</button>
<p>States: {mementos.length}, Current: {currentIndex + 1}</p>
</div>
);
}Iterator pattern for sequential access to collections.
- Iterator: Traverses collection
- Aggregate: Creates iterator
- Benefits: Uniform traversal
- Use case: Collection traversal
// Mediator pattern in React
function MediatorExample() {
const [messages, setMessages] = useState([]);
const [users, setUsers] = useState([]);
class Mediator {
constructor() {
this.users = [];
}
register(user) {
this.users.push(user);
user.setMediator(this);
}
send(message, sender) {
this.users.forEach(user => {
if (user !== sender) {
user.receive(message);
}
});
}
}
class User {
constructor(name) {
this.name = name;
this.mediator = null;
}
setMediator(mediator) {
this.mediator = mediator;
}
send(message) {
this.mediator.send(message, this);
}
receive(message) {
setMessages(prev => [...prev, `${this.name} received: ${message}`]);
}
}
const mediator = new Mediator();
const addUser = (name) => {
const user = new User(name);
mediator.register(user);
setUsers(prev => [...prev, user]);
};
const sendMessage = (senderName, message) => {
const sender = users.find(u => u.name === senderName);
if (sender) {
sender.send(message);
}
};
return (
<div>
<h3>Mediator Pattern</h3>
<button onClick={() => addUser(`User ${users.length + 1}`)}>Add User</button>
<div>
<h4>Users:</h4>
<ul>
{users.map((user, i) => (
<li key={i}>
{user.name}
<button onClick={() => sendMessage(user.name, 'Hello from ' + user.name)}>
Send
</button>
</li>
))}
</ul>
</div>
<div>
<h4>Messages:</h4>
<ul>
{messages.map((msg, i) => (
<li key={i}>{msg}</li>
))}
</ul>
</div>
</div>
);
}Template Method for algorithm skeletons.
- AbstractClass: Defines template
- ConcreteClass: Implements steps
- Benefits: Code reuse
- Use case: Frameworks
// Chain of Responsibility in React
function ChainExample() {
const [result, setResult] = useState('');
class Handler {
constructor() {
this.next = null;
}
setNext(handler) {
this.next = handler;
return handler;
}
handle(request) {
if (this.next) {
return this.next.handle(request);
}
return 'Request unhandled';
}
}
class AuthHandler extends Handler {
handle(request) {
if (request.token) {
setResult('Authentication passed');
return super.handle(request);
}
setResult('Authentication failed');
return 'Authentication failed';
}
}
class LoggerHandler extends Handler {
handle(request) {
setResult(prev => prev + '\nLogging request: ' + (request.url || 'unknown'));
return super.handle(request);
}
}
class ValidationHandler extends Handler {
handle(request) {
if (request.data) {
setResult(prev => prev + '\nValidation passed');
return super.handle(request);
}
setResult(prev => prev + '\nValidation failed');
return 'Validation failed';
}
}
const auth = new AuthHandler();
const logger = new LoggerHandler();
const validator = new ValidationHandler();
auth.setNext(logger).setNext(validator);
const handleValidRequest = () => {
setResult('');
auth.handle({ token: 'valid', url: '/api', data: 'payload' });
};
const handleInvalidRequest = () => {
setResult('');
auth.handle({ url: '/public' });
};
return (
<div>
<h3>Chain of Responsibility</h3>
<button onClick={handleValidRequest}>Valid Request</button>
<button onClick={handleInvalidRequest}>Invalid Request</button>
<pre>{result}</pre>
</div>
);
}Builder pattern for constructing complex objects.
- Builder: Constructs parts
- Director: Orchestrates construction
- Product: Constructed object
- Benefits: Step-by-step construction
// State pattern in React
function StateExample() {
const [state, setState] = useState('ready');
const handleState = () => {
switch (state) {
case 'ready':
setState('processing');
break;
case 'processing':
setState('completed');
break;
case 'completed':
setState('ready');
break;
default:
setState('ready');
}
};
const getStateMessage = () => {
switch (state) {
case 'ready':
return 'Ready: Waiting for input';
case 'processing':
return 'Processing: Working on task';
case 'completed':
return 'Completed: Task finished';
default:
return 'Unknown state';
}
};
const getStateColor = () => {
switch (state) {
case 'ready':
return '#4CAF50';
case 'processing':
return '#FF9800';
case 'completed':
return '#2196F3';
default:
return '#9E9E9E';
}
};
return (
<div>
<h3>State Pattern</h3>
<div
style={{
padding: '20px',
background: getStateColor(),
color: 'white',
borderRadius: '8px',
margin: '10px 0',
}}
>
{getStateMessage()}
</div>
<button onClick={handleState}>Transition</button>
<p>Current State: {state}</p>
</div>
);
}Prototype pattern for cloning objects using copy methods.
- Clone method: Creates a copy
- Shallow copy:
Object.assign() - Deep copy: Recursive copy or JSON
- Benefits: Object reuse, performance
// Proxy pattern in React
function ProxyExample() {
const [data, setData] = useState('');
const [realData, setRealData] = useState('');
class RealSubject {
request() {
return 'RealSubject: Handling request';
}
}
class Proxy {
constructor() {
this.realSubject = null;
}
request() {
if (!this.realSubject) {
setData(prev => prev + '\nProxy: Creating real subject');
this.realSubject = new RealSubject();
}
setData(prev => prev + '\nProxy: Using cached real subject');
return this.realSubject.request();
}
}
class LoggingProxy {
constructor(subject) {
this.subject = subject;
}
request() {
setData(prev => prev + '\nLogging: Request started');
const result = this.subject.request();
setData(prev => prev + '\nLogging: Request completed');
return result;
}
}
const proxy = new Proxy();
const handleProxy = () => {
setData('');
const result = proxy.request();
setData(prev => prev + '\nResult: ' + result);
};
const handleLoggingProxy = () => {
setData('');
const real = new RealSubject();
const loggingProxy = new LoggingProxy(real);
const result = loggingProxy.request();
setData(prev => prev + '\nResult: ' + result);
};
return (
<div>
<h3>Proxy Pattern</h3>
<button onClick={handleProxy}>Simple Proxy</button>
<button onClick={handleLoggingProxy}>Logging Proxy</button>
<pre>{data}</pre>
</div>
);
}Local Storage is a key-value storage system for persisting data in the browser.
- Set:
localStorage.setItem('key', 'value') - Get:
localStorage.getItem('key') - Remove:
localStorage.removeItem('key') - Clear:
localStorage.clear() - JSON:
JSON.stringify()andJSON.parse()
// Flyweight pattern in React
function FlyweightExample() {
const [flyweights, setFlyweights] = useState([]);
class Flyweight {
constructor(sharedState) {
this.sharedState = sharedState;
}
operation(uniqueState) {
return `Shared: ${this.sharedState}, Unique: ${uniqueState}`;
}
}
class FlyweightFactory {
constructor() {
this.flyweights = {};
}
getFlyweight(sharedState) {
if (!this.flyweights[sharedState]) {
this.flyweights[sharedState] = new Flyweight(sharedState);
}
return this.flyweights[sharedState];
}
getCount() {
return Object.keys(this.flyweights).length;
}
}
const factory = new FlyweightFactory();
const addFlyweight = (shared, unique) => {
const fw = factory.getFlyweight(shared);
const result = fw.operation(unique);
setFlyweights(prev => [...prev, { shared, unique, result }]);
};
return (
<div>
<h3>Flyweight Pattern</h3>
<button onClick={() => addFlyweight('state1', 'unique1')}>Add state1/unique1</button>
<button onClick={() => addFlyweight('state1', 'unique2')}>Add state1/unique2</button>
<button onClick={() => addFlyweight('state2', 'unique3')}>Add state2/unique3</button>
<p>Flyweights created: {factory.getCount()}</p>
<div>
<h4>Operations:</h4>
<ul>
{flyweights.map((fw, i) => (
<li key={i}>{fw.result}</li>
))}
</ul>
</div>
</div>
);
}Networking in React uses fetch or axios for HTTP requests with async/await and error handling.
- GET:
fetch(url).then(res => res.json()) - POST:
fetch(url, { method: 'POST', body: JSON.stringify(data) }) - Headers:
{ headers: { 'Content-Type': 'application/json' } } - Error handling:
try { } catch (error) { } - Abort: AbortController for canceling requests
// Bridge pattern in React
function BridgeExample() {
const [impl, setImpl] = useState('A');
const [result, setResult] = useState('');
class Implementation {
operation() {
return '';
}
}
class ConcreteImplementationA extends Implementation {
operation() {
return 'ConcreteImplementationA: Operation';
}
}
class ConcreteImplementationB extends Implementation {
operation() {
return 'ConcreteImplementationB: Operation';
}
}
class Abstraction {
constructor(implementation) {
this.implementation = implementation;
}
operation() {
return this.implementation.operation();
}
}
class ExtendedAbstraction extends Abstraction {
operation() {
return 'ExtendedAbstraction: ' + this.implementation.operation();
}
}
class AlternativeAbstraction extends Abstraction {
operation() {
return 'AlternativeAbstraction: ' + this.implementation.operation();
}
}
const handleOperation = () => {
const impl = impl === 'A'
? new ConcreteImplementationA()
: new ConcreteImplementationB();
const abstraction = new ExtendedAbstraction(impl);
const alternative = new AlternativeAbstraction(impl);
setResult(`Extended: ${abstraction.operation()}\nAlternative: ${alternative.operation()}`);
};
return (
<div>
<h3>Bridge Pattern</h3>
<select value={impl} onChange={(e) => setImpl(e.target.value)}>
<option value="A">Implementation A</option>
<option value="B">Implementation B</option>
</select>
<button onClick={handleOperation}>Execute</button>
<pre>{result}</pre>
</div>
);
}Image handling in React uses the img tag with network, local, and base64 image sources.
- Network:
<img src="https://example.com/image.jpg" /> - Local:
<img src={require('./image.png')} /> - Base64:
<img src="data:image/png;base64,..." /> - Lazy loading:
loading="lazy" - Image optimization:
srcSetfor responsive images
// Adapter pattern in React
function AdapterExample() {
const [result, setResult] = useState('');
class Target {
request() {
return 'Target: Request';
}
}
class Adaptee {
specificRequest() {
return 'Adaptee: Specific Request';
}
}
class Adapter extends Target {
constructor(adaptee) {
super();
this.adaptee = adaptee;
}
request() {
return this.adaptee.specificRequest();
}
}
class LoggingAdapter extends Adapter {
constructor(adaptee) {
super(adaptee);
}
request() {
setResult(prev => prev + '\nAdapter: Logging request');
return super.request();
}
}
const handleTarget = () => {
const target = new Target();
setResult('Target: ' + target.request());
};
const handleAdapter = () => {
const adaptee = new Adaptee();
const adapter = new Adapter(adaptee);
setResult('Adapter: ' + adapter.request());
};
const handleLogging = () => {
setResult('');
const adaptee = new Adaptee();
const adapter = new LoggingAdapter(adaptee);
const result = adapter.request();
setResult(prev => prev + '\nResult: ' + result);
};
return (
<div>
<h3>Adapter Pattern</h3>
<button onClick={handleTarget}>Target</button>
<button onClick={handleAdapter}>Adapter</button>
<button onClick={handleLogging}>Logging Adapter</button>
<pre>{result}</pre>
</div>
);
}Animations in React are implemented using CSS transitions, CSS animations, or libraries like Framer Motion.
- CSS transitions:
transition: all 0.3s - CSS animations:
@keyframes - Framer Motion:
motion.div - React Spring: Spring-based animations
- GSAP: GreenSock Animation Platform
// Facade pattern in React
function FacadeExample() {
const [result, setResult] = useState('');
class SubsystemA {
operationA() {
return 'SubsystemA: Operation';
}
}
class SubsystemB {
operationB() {
return 'SubsystemB: Operation';
}
}
class SubsystemC {
operationC() {
return 'SubsystemC: Operation';
}
}
class Facade {
constructor() {
this.subsystemA = new SubsystemA();
this.subsystemB = new SubsystemB();
this.subsystemC = new SubsystemC();
}
simpleOperation() {
return this.subsystemA.operationA();
}
complexOperation() {
return [
this.subsystemA.operationA(),
this.subsystemB.operationB(),
this.subsystemC.operationC(),
].join('\n');
}
}
const facade = new Facade();
const handleSimple = () => {
setResult(facade.simpleOperation());
};
const handleComplex = () => {
setResult(facade.complexOperation());
};
return (
<div>
<h3>Facade Pattern</h3>
<button onClick={handleSimple}>Simple Operation</button>
<button onClick={handleComplex}>Complex Operation</button>
<pre>{result}</pre>
</div>
);
}Event handling in React uses JSX event handlers like onClick, onChange, and onSubmit.
- onClick:
<button onClick={handleClick}>Click</button> - onChange:
<input onChange={handleChange} /> - onSubmit:
<form onSubmit={handleSubmit}> - Synthetic events: React's wrapper for native events
- Event pooling: Events are pooled for performance
// Composite pattern in React
function CompositeExample() {
const [components, setComponents] = useState([]);
class Component {
constructor(name) {
this.name = name;
}
operation() {
return '';
}
add(component) {
throw new Error('Cannot add to leaf');
}
remove(component) {
throw new Error('Cannot remove from leaf');
}
}
class Leaf extends Component {
operation() {
return `Leaf ${this.name}: Operation`;
}
}
class Composite extends Component {
constructor(name) {
super(name);
this.children = [];
}
operation() {
const childResults = this.children.map(child => child.operation());
return `Composite ${this.name}: Operation\n${childResults.join('\n')}`;
}
add(component) {
this.children.push(component);
}
remove(component) {
this.children = this.children.filter(child => child !== component);
}
countLeaves() {
let count = 0;
for (const child of this.children) {
if (child instanceof Leaf) {
count++;
} else {
count += child.countLeaves();
}
}
return count;
}
}
const buildComposite = () => {
const leaf1 = new Leaf('A');
const leaf2 = new Leaf('B');
const leaf3 = new Leaf('C');
const leaf4 = new Leaf('D');
const composite1 = new Composite('Comp1');
composite1.add(leaf1);
composite1.add(leaf2);
const composite2 = new Composite('Comp2');
composite2.add(leaf3);
composite2.add(composite1);
const root = new Composite('Root');
root.add(leaf4);
root.add(composite2);
setComponents([root]);
};
return (
<div>
<h3>Composite Pattern</h3>
<button onClick={buildComposite}>Build Composite</button>
{components.map((comp, i) => (
<div key={i}>
<h4>Operation Result:</h4>
<pre>{comp.operation()}</pre>
<p>Leaves count: {comp.countLeaves()}</p>
</div>
))}
</div>
);
}Portals in React allow rendering children into a different DOM node outside the parent component's hierarchy.
- ReactDOM.createPortal:
ReactDOM.createPortal(children, domNode) - Modals: Render modals at root level
- Tooltips: Render tooltips outside parent
- Event bubbling: Events still bubble through React tree
- Accessibility: Maintains focus management
// Visitor pattern in React
function VisitorExample() {
const [results, setResults] = useState([]);
class Element {
constructor(data) {
this.data = data;
}
accept(visitor) {}
}
class ElementA extends Element {
accept(visitor) {
return visitor.visitA(this);
}
}
class ElementB extends Element {
accept(visitor) {
return visitor.visitB(this);
}
}
class Visitor {
visitA(element) {}
visitB(element) {}
}
class ConcreteVisitor extends Visitor {
visitA(element) {
return `Visiting ElementA: ${element.data}`;
}
visitB(element) {
return `Visiting ElementB: ${element.data}`;
}
}
class CountingVisitor extends Visitor {
constructor() {
super();
this.countA = 0;
this.countB = 0;
}
visitA(element) {
this.countA++;
return `Visiting ElementA (${this.countA}): ${element.data}`;
}
visitB(element) {
this.countB++;
return `Visiting ElementB (${this.countB}): ${element.data}`;
}
}
const elements = [
new ElementA('Hello'),
new ElementB('World'),
new ElementA('React'),
new ElementB('Visitor'),
];
const handleVisit = () => {
const visitor = new ConcreteVisitor();
const results = elements.map(el => el.accept(visitor));
setResults(results);
};
const handleCounting = () => {
const visitor = new CountingVisitor();
const results = elements.map(el => el.accept(visitor));
setResults([...results, `Counts: A=${visitor.countA}, B=${visitor.countB}`]);
};
return (
<div>
<h3>Visitor Pattern</h3>
<button onClick={handleVisit}>Standard Visitor</button>
<button onClick={handleCounting}>Counting Visitor</button>
<div>
<h4>Results:</h4>
<ul>
{results.map((r, i) => (
<li key={i}>{r}</li>
))}
</ul>
</div>
</div>
);
}Refs in React provide a way to access DOM nodes or React elements directly. They are created using useRef.
- useRef:
const ref = useRef(null) - Access DOM:
ref.current.focus() - Forward refs:
forwardRef - Callback refs:
ref={node => setNode(node)} - Mutable values: Store mutable values without re-renders
// Iterator pattern in React
function IteratorExample() {
const [items, setItems] = useState(['A', 'B', 'C', 'D', 'E']);
const [iterated, setIterated] = useState([]);
class Iterator {
constructor(collection) {
this.collection = collection;
this.position = 0;
}
current() {
return this.collection[this.position] || null;
}
key() {
return this.position;
}
next() {
this.position++;
}
rewind() {
this.position = 0;
}
valid() {
return this.position < this.collection.length;
}
}
class ReverseIterator {
constructor(collection) {
this.collection = collection;
this.position = collection.length - 1;
}
current() {
return this.collection[this.position] || null;
}
key() {
return this.position;
}
next() {
this.position--;
}
rewind() {
this.position = this.collection.length - 1;
}
valid() {
return this.position >= 0;
}
}
const handleIterate = () => {
const iterator = new Iterator(items);
const result = [];
while (iterator.valid()) {
result.push(iterator.current());
iterator.next();
}
setIterated(result);
};
const handleReverse = () => {
const iterator = new ReverseIterator(items);
const result = [];
while (iterator.valid()) {
result.push(iterator.current());
iterator.next();
}
setIterated(result);
};
return (
<div>
<h3>Iterator Pattern</h3>
<p>Collection: {items.join(', ')}</p>
<button onClick={handleIterate}>Forward Iteration</button>
<button onClick={handleReverse}>Reverse Iteration</button>
<p>Result: {iterated.join(', ')}</p>
</div>
);
}Render props is a pattern for sharing code between components using a prop that is a function.
- Render prop:
<DataProvider render={data => <Component data={data} />} /> - Children as function:
<DataProvider>{data => <Component data={data} />}</DataProvider> - Data fetching: Share fetch logic
- Mouse tracking: Share mouse position
- Alternative: Custom hooks (preferred approach)
// Template Method pattern in React
function TemplateExample() {
const [result, setResult] = useState('');
class Template {
templateMethod() {
return [
this.step1(),
this.step2(),
this.step3(),
].join('\n');
}
step1() { return ''; }
step2() { return ''; }
step3() { return ''; }
}
class DefaultTemplate extends Template {
step1() { return 'Step 1'; }
step2() { return 'Step 2'; }
step3() { return 'Step 3'; }
}
class LoggingTemplate extends Template {
constructor(template) {
super();
this.template = template;
}
step1() {
const result = this.template.step1();
return `Logging: ${result}`;
}
step2() {
const result = this.template.step2();
return `Logging: ${result}`;
}
step3() {
const result = this.template.step3();
return `Logging: ${result}`;
}
}
class DataProcessingTemplate extends Template {
constructor(data) {
super();
this.data = data;
}
step1() {
return `Processing data: ${this.data} - Step 1`;
}
step2() {
return `Processing data: ${this.data} - Step 2`;
}
step3() {
return `Processing data: ${this.data} - Step 3`;
}
}
const handleDefault = () => {
const template = new DefaultTemplate();
setResult(template.templateMethod());
};
const handleLogging = () => {
const defaultTemplate = new DefaultTemplate();
const template = new LoggingTemplate(defaultTemplate);
setResult(template.templateMethod());
};
const handleData = () => {
const template = new DataProcessingTemplate('example');
setResult(template.templateMethod());
};
return (
<div>
<h3>Template Method Pattern</h3>
<button onClick={handleDefault}>Default Template</button>
<button onClick={handleLogging}>Logging Template</button>
<button onClick={handleData}>Data Template</button>
<pre>{result}</pre>
</div>
);
}Debugging in React uses React Developer Tools, console.log, and breakpoints for development.
- React DevTools: Component inspection
- Console.log: Logging to browser console
- Breakpoints: In-source debugging
- Error boundaries: Catch component errors
- Profiler: Performance profiling
// Builder pattern in React
function BuilderExample() {
const [product, setProduct] = useState(null);
class Product {
constructor() {
this.parts = [];
}
addPart(part) {
this.parts.push(part);
}
listParts() {
return this.parts.join(', ');
}
}
class Builder {
constructor() {
this.reset();
}
reset() {
this.product = new Product();
}
buildStepA() {
this.product.addPart('Part A');
}
buildStepB() {
this.product.addPart('Part B');
}
buildStepC() {
this.product.addPart('Part C');
}
getResult() {
const result = this.product;
this.reset();
return result;
}
}
class Director {
constructor(builder) {
this.builder = builder;
}
buildMinimal() {
this.builder.buildStepA();
}
buildFull() {
this.builder.buildStepA();
this.builder.buildStepB();
this.builder.buildStepC();
}
buildCustom(steps) {
this.builder.reset();
steps.forEach(step => {
switch(step) {
case 'A': this.builder.buildStepA(); break;
case 'B': this.builder.buildStepB(); break;
case 'C': this.builder.buildStepC(); break;
}
});
}
}
const builder = new Builder();
const director = new Director(builder);
const handleMinimal = () => {
director.buildMinimal();
setProduct(builder.getResult());
};
const handleFull = () => {
director.buildFull();
setProduct(builder.getResult());
};
const handleCustom = () => {
director.buildCustom(['C', 'A', 'B']);
setProduct(builder.getResult());
};
return (
<div>
<h3>Builder Pattern</h3>
<button onClick={handleMinimal}>Build Minimal</button>
<button onClick={handleFull}>Build Full</button>
<button onClick={handleCustom}>Build Custom</button>
{product && (
<div>
<h4>Product:</h4>
<p>{product.listParts()}</p>
</div>
)}
</div>
);
}Performance optimization in React includes memoization, code splitting, and virtualized lists.
- useMemo: Memoize expensive calculations
- useCallback: Memoize functions
- React.memo: Prevent unnecessary re-renders
- Lazy loading:
React.lazyandSuspense - Virtualized lists:
react-windowfor large lists
// Prototype pattern in React
function PrototypeExample() {
const [original, setOriginal] = useState({ name: 'Original', value: 42 });
const [clones, setClones] = useState([]);
const [deepClones, setDeepClones] = useState([]);
class Prototype {
constructor(data) {
this.data = data;
}
clone() {
return new Prototype({ ...this.data });
}
deepClone() {
return new Prototype(JSON.parse(JSON.stringify(this.data)));
}
}
class MutablePrototype extends Prototype {
setData(data) {
this.data = data;
}
}
const prototype = new Prototype(original);
const handleClone = () => {
const clone = prototype.clone();
setClones(prev => [...prev, clone.data]);
};
const handleDeepClone = () => {
const deepClone = prototype.deepClone();
setDeepClones(prev => [...prev, deepClone.data]);
};
const handleModify = () => {
setOriginal({ ...original, value: original.value + 1 });
};
return (
<div>
<h3>Prototype Pattern</h3>
<button onClick={handleModify}>Modify Original</button>
<button onClick={handleClone}>Clone</button>
<button onClick={handleDeepClone}>Deep Clone</button>
<div>
<h4>Original:</h4>
<pre>{JSON.stringify(original, null, 2)}</pre>
</div>
<div>
<h4>Clones ({clones.length}):</h4>
<ul>
{clones.map((clone, i) => (
<li key={i}>{JSON.stringify(clone)}</li>
))}
</ul>
</div>
<div>
<h4>Deep Clones ({deepClones.length}):</h4>
<ul>
{deepClones.map((clone, i) => (
<li key={i}>{JSON.stringify(clone)}</li>
))}
</ul>
</div>
</div>
);
}