Syntax:
function ComponentName() { return <div>Hello</div>; } class ComponentName extends React.Component { render() { return <div>Hello</div>; } }
Syntax:
function MyComponent() { return <div>Content</div>; } export default MyComponent;
Example 1:
function Greeting() { // Simple greeting component return <h1>Hello, World!</h1>; } export default Greeting;
Output: Displays "Hello, World!" as a heading.
Example 2:
function Welcome(props) { // Receives props and displays them return <p>Welcome, {props.name}!</p>; } export default Welcome;
Output: Shows "Welcome, [name]!" based on props.
Example 3:
function Sum() { // Displays result of addition const a = 5; const b = 10; return <div>Sum is: {a + b}</div>; } export default Sum;
Output: Shows "Sum is: 15".
Syntax:
class MyComponent extends React.Component { render() { return <div>Content</div>; } } export default MyComponent;
Example 1:
class Greeting extends React.Component { render() { return <h1>Hello, Class!</h1>; } } export default Greeting;
Output: Displays "Hello, Class!".
Example 2:
class Welcome extends React.Component { render() { return <p>Welcome, {this.props.name}!</p>; } } export default Welcome;
Output: Displays "Welcome, [name]!" based on props.
Example 3:
class Sum extends React.Component { render() { const a = 20; const b = 30; return <div>Sum is: {a + b}</div>; } } export default Sum;
Output: Displays "Sum is: 50".
Syntax:
function Parent() { return ( <div> <Child /> </div> ); }
Example 1:
function Header() { return <h1>Site Header</h1>; } function Page() { return ( <div> <Header /> </div> ); } export default Page;
Output: Displays the header component inside a page.
Example 2:
function Name(props) { return <p>Name: {props.name}</p>; } function Profile() { return ( <div> <Name name="Alice" /> </div> ); } export default Profile;
Output: Displays "Name: Alice".
Example 3:
function Info() { return <p>This is some info.</p>; } function Layout() { return ( <section> <Info /> </section> ); } export default Layout;
Output: Renders the Info inside a section tag.
Syntax:
const element = <h1>Hello, JSX!</h1>; const container = <div><p>Nested</p></div>;
Example 1:
function Greeting() { // Returns an H1 element with JSX return <h1>Hello, JSX!</h1>; } export default Greeting;
Output: Displays "Hello, JSX!" as a heading.
Example 2:
function Container() { // Uses JSX to nest elements return ( <div> <h2>Title</h2> <p>Description</p> </div> ); } export default Container;
Output: Displays "Title" and "Description" inside a <div>.
Example 3:
function ShowList() { // JSX used with array map const items = ['Apple', 'Banana', 'Orange']; return ( <ul> {items.map((item, index) => <li key={index}>{item}</li>)} </ul> ); } export default ShowList;
Output: Displays a bulleted list of items.
Syntax:
// Use camelCase for attributes: className, htmlFor // Wrap multiple elements in a parent tag
Example 1:
function Label() { return <label htmlFor="name">Name:</label>; } export default Label;
Output: Displays a label for the input field with correct attribute.
Example 2:
function Wrapper() { return ( <div> <h1>Header</h1> <p>Paragraph</p> </div> ); } export default Wrapper;
Output: Renders both elements wrapped in a single div.
Example 3:
function InputField() { return <input type="text" placeholder="Enter name" />; } export default InputField;
Output: Displays a text input field with placeholder text.
Syntax:
const name = 'Alice'; const greeting = <h1>Hello, {name}</h1>;
Example 1:
function Greet() { const name = "John"; return <h1>Hello, {name}</h1>; } export default Greet;
Output: Displays "Hello, John".
Example 2:
function Calc() { const a = 3; const b = 7; return <p>Sum: {a + b}</p>; } export default Calc;
Output: Displays "Sum: 10".
Example 3:
function DateInfo() { const today = new Date().toDateString(); return <div>Today is {today}</div>; } export default DateInfo;
Output: Displays current date.
Syntax:
// class becomes className // for becomes htmlFor // self-closing tags must be closed like <br />
Example 1:
function HtmlCompare() { return <div className="box">Box Content</div>; } export default HtmlCompare;
Output: Applies class "box" to the div.
Example 2:
function LabelInput() { return ( <div> <label htmlFor="email">Email:</label> <input id="email" type="email" /> </div> ); } export default LabelInput;
Output: Displays a labeled input for email.
Example 3:
function LineBreak() { return ( <div> Line 1<br /> Line 2 </div> ); } export default LineBreak;
Output: Displays "Line 1" and "Line 2" with a line break.
Syntax:
function Welcome(props) { return <h1>Hello, {props.name}</h1>; } Welcome.defaultProps = { name: 'Guest' };
Example 1:
function Welcome(props) { // Accepts a 'name' prop and uses it inside JSX return <h1>Hello, {props.name}</h1>; } export default function App() { // Passing prop 'name' with value "Alice" return <Welcome name="Alice" />; }
Output: Displays "Hello, Alice".
Example 2:
function UserInfo(props) { // Multiple props being used return <p>{props.name} is {props.age} years old.</p>; } export default function App() { return <UserInfo name="Bob" age={28} />; }
Output: Displays "Bob is 28 years old."
Example 3:
function Greeting(props) { // Displays default if no prop is passed return <h1>Welcome, {props.name}</h1>; } Greeting.defaultProps = { name: 'Visitor' }; export default function App() { return <Greeting />; }
Output: Displays "Welcome, Visitor".
Syntax:
function Grandparent(props) { return <Parent name={props.name} />; } function Parent(props) { return <Child name={props.name} />; } function Child(props) { return <p>Hi, {props.name}</p>; }
Example 1:
function Child(props) { return <div>Hello, {props.name}</div>; } function Parent(props) { return <Child name={props.name} />; } function App() { return <Parent name="John" />; } export default App;
Output: Displays "Hello, John".
Example 2:
const Child = ({ message }) => <p>{message}</p>; const Parent = ({ message }) => <Child message={message} />; const Grandparent = () => <Parent message="Deep Prop" />; export default Grandparent;
Output: Displays "Deep Prop".
Example 3:
function C(props) { return <span>{props.value}</span>; } function B(props) { return <C value={props.value} />; } function A() { return <B value="Passed from A" />; } export default A;
Output: Displays "Passed from A".
Syntax:
function Wrapper(props) { return <div>{props.children}</div>; }
Example 1:
function Wrapper(props) { return <section>{props.children}</section>; } export default function App() { return ( <Wrapper> <h2>Inside Wrapper</h2> </Wrapper> ); }
Output: Displays "Inside Wrapper" inside a <section>.
Example 2:
function Card(props) { return <div className="card">{props.children}</div>; } function App() { return ( <Card> <p>Card Content</p> </Card> ); } export default App;
Output: Renders a div with class "card" containing paragraph.
Example 3:
const Container = ({ children }) => ( <div style={{ border: '1px solid black' }}>{children}</div> ); function App() { return ( <Container> <h1>With Border</h1> </Container> ); } export default App;
Output: Displays an H1 with a border around it.
Syntax:
const [state, setState] = useState(initialValue); this.setState({ key: value }); // For class components
Example 1:
import React, { useState } from 'react'; function Counter() { // Initialize state variable 'count' to 0 const [count, setCount] = useState(0); // Function to increment count return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); } export default Counter;
Output: Button increases the displayed count.
Example 2:
function Toggle() { const [isOn, setIsOn] = useState(true); return ( <button onClick={() => setIsOn(!isOn)}> {isOn ? 'ON' : 'OFF'} </button> ); } export default Toggle;
Output: Toggles between "ON" and "OFF" text.
Example 3:
function InputExample() { const [text, setText] = useState(''); return ( <input type="text" value={text} onChange={(e) => setText(e.target.value)} /> ); } export default InputExample;
Output: Input field updates state as text is entered.
Example 1:
import React, { Component } from 'react'; class Counter extends Component { constructor(props) { super(props); this.state = { count: 0 }; } increment = () => { this.setState({ count: this.state.count + 1 }); }; render() { return ( <div> <p>Count: {this.state.count}</p> <button onClick={this.increment}>Increment</button> </div> ); } } export default Counter;
Output: Button increments counter in a class component.
Example 2:
class Toggle extends Component { state = { isVisible: true }; toggle = () => { this.setState({ isVisible: !this.state.isVisible }); }; render() { return ( <div> <button onClick={this.toggle}>Toggle</button> {this.state.isVisible && <p>Visible Text</p>} </div> ); } } export default Toggle;
Output: Button toggles visibility of text.
Example 3:
class Form extends Component { state = { input: '' }; handleChange = (e) => { this.setState({ input: e.target.value }); }; render() { return ( <input type="text" value={this.state.input} onChange={this.handleChange} /> ); } } export default Form;
Output: Controlled input with class state management.
Example 1:
function Child({ count }) { return <p>Count: {count}</p>; } function Parent() { const [count, setCount] = useState(0); return ( <div> <Child count={count} /> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); } export default Parent;
Output: Parent manages state; child reads it.
Example 2:
function Display({ text }) { return <p>{text}</p>; } function Editor({ onChange }) { return <input onChange={(e) => onChange(e.target.value)} />; } function App() { const [text, setText] = useState(''); return ( <> <Editor onChange={setText} /> <Display text={text} /> </> ); } export default App;
Output: Input updates state; display reflects change.
Example 3:
function Slider({ value, onSlide }) { return <input type="range" value={value} onChange={(e) => onSlide(e.target.value)} />; } function ValueDisplay({ value }) { return <div>Value: {value}</div>; } function Controller() { const [val, setVal] = useState(10); return ( <> <Slider value={val} onSlide={setVal} /> <ValueDisplay value={val} /> </> ); } export default Controller;
Output: Slider control managed at parent, passed to children.
Example 1:
function Derived() { const [items, setItems] = useState([1, 2, 3]); const count = items.length; // derived state return <p>You have {count} items.</p>; } export default Derived;
Output: Displays number of items in list.
Example 2:
function Temperature({ celsius }) { const fahrenheit = (celsius * 9) / 5 + 32; // derived return <p>{celsius}°C = {fahrenheit}°F</p>; } export default Temperature;
Output: Displays converted temperature.
Example 3:
function WordCount({ text }) { const wordCount = text.split(' ').length; return <p>Word Count: {wordCount}</p>; } export default WordCount;
Output: Displays number of words in text.
// Syntax: const [state, setState] = useState(initialValue); // Example 1 import React, { useState } from 'react'; function Counter() { const [count, setCount] = useState(0); // declare state variable return ( <div> <p>Count: {count}</p> {/* display count */} <button onClick={() => setCount(count + 1)}>Increment</button> {/* update state */} </div> ); } // Output: // A button that shows count and increments on click. // Example 2 function Toggle() { const [isOn, setIsOn] = useState(true); return ( <div> <p>Status: {isOn ? 'On' : 'Off'}</p> <button onClick={() => setIsOn(!isOn)}>Toggle</button> </div> ); } // Output: // A toggle button that switches between 'On' and 'Off'.
// Syntax: useEffect(() => { // side effects return () => { // cleanup (optional) }; }, [dependencies]); // Example 1 - Mount useEffect(() => { console.log('Component mounted'); }, []); // empty array = run only once // Example 2 - Update useEffect(() => { console.log('State updated'); }, [state]); // run when 'state' changes // Example 3 - Unmount useEffect(() => { const timer = setInterval(() => console.log('Tick'), 1000); return () => clearInterval(timer); // cleanup }, []); // Output: // Log messages on mount/update, and clear interval on unmount.
// Syntax: const value = useContext(MyContext); // Example 1 const ThemeContext = React.createContext('light'); function DisplayTheme() { const theme = useContext(ThemeContext); return <p>Theme: {theme}</p>; } // Example 2 function App() { return ( <ThemeContext.Provider value="dark"> <DisplayTheme /> </ThemeContext.Provider> ); } // Output: // 'Theme: dark' rendered from context.
// Syntax: const [state, dispatch] = useReducer(reducer, initialArg); // Example const reducer = (state, action) => { switch (action.type) { case 'increment': return { count: state.count + 1 }; default: return state; } }; function Counter() { const [state, dispatch] = useReducer(reducer, { count: 0 }); return ( <div> Count: {state.count} <button onClick={() => dispatch({ type: 'increment' })}>+</button> </div> ); } // Output: // Count displayed and incremented using reducer logic.
// Syntax: const refContainer = useRef(initialValue); // Example 1 - DOM Access const inputRef = useRef(null); useEffect(() => { inputRef.current.focus(); // focus on mount }, []); // Example 2 - Store mutable value const count = useRef(0); useEffect(() => { count.current += 1; console.log(count.current); }); // Output: // Access and persist DOM or data across renders.
// Syntax: const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]); // Example const expensiveCalculation = (num) => { console.log('Calculating...'); return num * 2; }; const result = useMemo(() => expensiveCalculation(5), []); // Output: // Expensive function only recalculates when dependencies change.
// Syntax: const memoizedCallback = useCallback(() => { doSomething(a, b); }, [a, b]); // Example const handleClick = useCallback(() => { console.log('Clicked'); }, []); // Output: // Function remains the same reference across renders unless dependencies change.
// Similar to useEffect, but fires synchronously after DOM changes useLayoutEffect(() => { console.log('Layout effect ran'); }, []); // Output: // Executes before paint, useful for layout measurement.
// Syntax: useDebugValue(value); // Example - used in custom hooks function useCustomHook() { const [data, setData] = useState(null); useDebugValue(data ? 'Loaded' : 'Loading'); return data; } // Output: // Helps with debugging custom hook states in React DevTools.
function useCounter() { const [count, setCount] = useState(0); const increment = () => setCount((c) => c + 1); return { count, increment }; } function CounterComponent() { const { count, increment } = useCounter(); return ( <div> <p>{count}</p> <button onClick={increment}>Increment</button> </div> ); }
// useFetch function useFetch(url) { const [data, setData] = useState(null); useEffect(() => { fetch(url) .then((res) => res.json()) .then(setData); }, [url]); return data; } // useLocalStorage function useLocalStorage(key, initialValue) { const [storedValue, setStoredValue] = useState(() => { const item = localStorage.getItem(key); return item ? JSON.parse(item) : initialValue; }); const setValue = (value) => { setStoredValue(value); localStorage.setItem(key, JSON.stringify(value)); }; return [storedValue, setValue]; } // Output: // Custom hooks encapsulate reusable logic like fetching or localStorage.
// Called once after initial render class MyComponent extends React.Component { componentDidMount() { console.log('Component mounted'); } render() { returnHello; } } // Example 2 class FetchData extends React.Component { state = { data: null }; componentDidMount() { fetch('https://api.example.com') .then(res => res.json()) .then(data => this.setState({ data })); } render() { return{this.state.data}; } } // Output: Logs to console after mount, or fetches data.
// Called after component updates class Counter extends React.Component { componentDidUpdate(prevProps) { if (prevProps.count !== this.props.count) { console.log('Count updated'); } } render() { return{this.props.count}; } } // Output: Logs only when count changes.
// Cleanup before component unmounts class Timer extends React.Component { componentDidMount() { this.interval = setInterval(() => console.log('tick'), 1000); } componentWillUnmount() { clearInterval(this.interval); } render() { returnRunning...; } } // Output: Interval is cleared on unmount.
class Optimized extends React.Component { shouldComponentUpdate(nextProps) { return nextProps.value !== this.props.value; } render() { return{this.props.value}; } } // Output: Renders only if value prop changes.
useEffect(() => { console.log('Mounted'); }, []); // Run once useEffect(() => { console.log('Count changed'); }, [count]); // Run when count changes
useEffect(() => { const id = setInterval(() => console.log('tick'), 1000); return () => clearInterval(id); // Cleanup }, []); // Output: Interval is cleared when component unmounts.
useEffect(() => { let isActive = true; fetch('/data').then(res => res.json()).then(data => { if (isActive) { setData(data); } }); return () => { isActive = false; }; }, []); // Output: Prevents setting state on unmounted component.
// Syntax const DataProvider = ({ render }) => { const data = 'React'; return render(data); }; // Example 1 const App = () => ( <DataProvider render={(data) => <h1>Hello {data}</h1>} /> ); // Example 2 const MouseTracker = ({ render }) => { const [position, setPosition] = React.useState({ x: 0, y: 0 }); return <div onMouseMove={(e) => setPosition({ x: e.clientX, y: e.clientY })}> {render(position)} </div>; }; const App2 = () => ( <MouseTracker render={({ x, y }) => <p>{x}, {y}</p>} /> );
// Syntax const withTitle = (Component) => { return function Wrapper(props) { return <h1><Component {...props} /></h1>; }; }; // Example 1 const Title = ({ text }) => <span>{text}</span>; const EnhancedTitle = withTitle(Title); // Example 2 const Button = ({ label }) => <button>{label}</button>; const StyledButton = withTitle(Button);
// Syntax & Example const Tabs = ({ children }) => <div>{children}</div>; Tabs.Tab = ({ label, children }) => <div><h2>{label}</h2>{children}</div>; const App = () => ( <Tabs> <Tabs.Tab label="Tab 1">Content 1</Tabs.Tab> <Tabs.Tab label="Tab 2">Content 2</Tabs.Tab> </Tabs> );
const MyContext = React.createContext();
const MyComponent = () => { const value = React.useContext(MyContext); return <p>{value}</p>; };
const MyContext = React.createContext(); const App = () => ( <MyContext.Provider value="Hello"> <MyComponent /> </MyContext.Provider> ); const MyComponent = () => { const value = React.useContext(MyContext); return <p>{value}</p>; };
// Redux Setup const reducer = (state = { count: 0 }, action) => { switch (action.type) { case 'INCREMENT': return { count: state.count + 1 }; default: return state; } }; const store = Redux.createStore(reducer);
import create from 'zustand'; const useStore = create((set) => ({ count: 0, inc: () => set((s) => ({ count: s.count + 1 })) })); const Counter = () => { const { count, inc } = useStore(); return <button onClick={inc}>{count}</button>; };
import { atom, selector, useRecoilState, RecoilRoot } from 'recoil'; const countAtom = atom({ key: 'count', default: 0 }); const Counter = () => { const [count, setCount] = useRecoilState(countAtom); return <button onClick={() => setCount(count + 1)}>{count}</button>; };
import { makeAutoObservable } from 'mobx'; import { observer } from 'mobx-react-lite'; class Store { count = 0; constructor() { makeAutoObservable(this); } increment() { this.count++; } } const store = new Store(); const Counter = observer(() => ( <button onClick={() => store.increment()}>{store.count}</button> ));
class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false }; } componentDidCatch(error, info) { this.setState({ hasError: true }); } render() { if (this.state.hasError) { return <h1>Something went wrong.</h1>; } return this.props.children; } }
// Syntax const MyComponent = React.memo((props) => { return <div>{props.name}</div>; }); // Example 1 const Greeting = React.memo(({ name }) => { return <h1>Hello, {name}</h1>; }); // Example 2 const Counter = React.memo(({ count }) => { console.log('Rendering Counter'); return <p>Count: {count}</p>; });
// useMemo Example 1 const ExpensiveComponent = ({ items }) => { const total = React.useMemo(() => { return items.reduce((a, b) => a + b, 0); }, [items]); return <div>Total: {total}</div>; }; // useMemo Example 2 const SortedList = ({ list }) => { const sorted = React.useMemo(() => [...list].sort(), [list]); return <ul>{sorted.map(i => <li key={i}>{i}</li>)}</ul>; }; // useCallback Example const Button = React.memo(({ onClick }) => { console.log('Button rendered'); return <button onClick={onClick}>Click me</button>; }); const App = () => { const [count, setCount] = React.useState(0); const handleClick = React.useCallback(() => setCount(c => c + 1), []); return <Button onClick={handleClick} />; };
// Syntax const LazyComponent = React.lazy(() => import('./MyComponent')); // Example 1 const App = () => ( <React.Suspense fallback={<div>Loading...</div>}> <LazyComponent /> </React.Suspense> ); // Example 2 const LazyPage = React.lazy(() => import('./Page')); const Main = () => ( <React.Suspense fallback={<p>Please wait...</p>}> <LazyPage /> </React.Suspense> );
// Using react-window import { FixedSizeList as List } from 'react-window'; const MyList = () => ( <List height={150} itemCount={1000} itemSize={35} width={300}> {({ index, style }) => <div style={style}>Item {index}</div>} </List> ); // Using react-virtualized import { List as RVList } from 'react-virtualized'; const rowRenderer = ({ key, index, style }) => ( <div key={key} style={style}>Row {index}</div> ); const VirtualizedList = () => ( <RVList height={200} rowCount={1000} rowHeight={30} width={300} rowRenderer={rowRenderer} /> );
// Keep component structure stable const StableComponent = ({ name }) => { return <div>Name: {name}</div>; }; // Example: Moving state to parent to avoid recreation const Parent = () => { const [value, setValue] = React.useState('React'); return <StableComponent name={value} />; };
// Always use unique & stable key const List = ({ items }) => ( <ul> {items.map(item => ( <li key={item.id}>{item.text}</li> ))} </ul> ); // Avoid using index as key when list changes frequently
// Use spread operator or immutable libraries const App = () => { const [list, setList] = React.useState(['A', 'B']); const addItem = () => { setList([...list, 'C']); }; return <button onClick={addItem}>Add</button>; }; // For nested state, use immutability helpers or immer
// Syntax import { BrowserRouter, Routes, Route } from 'react-router-dom'; // Example 1 const App = () => ( <BrowserRouter> <Routes> <Route path="/" element={<Home />} /> <Route path="/about" element={<About />} /> </Routes> </BrowserRouter> ); // Example 2 const RouterSetup = () => ( <BrowserRouter> <Routes> <Route path="/contact" element={<Contact />} /> <Route path="/services" element={<Services />} /> </Routes> </BrowserRouter> );
// Example 1 import { useParams } from 'react-router-dom'; const User = () => { const { id } = useParams(); return <div>User ID: {id}</div>; }; // Example 2 const Post = () => { const { postId } = useParams(); return <div>Post #{postId}</div>; };
// Example 1: useNavigate import { useNavigate } from 'react-router-dom'; const GoHome = () => { const navigate = useNavigate(); return <button onClick={() => navigate('/')}>Home</button>; }; // Example 2: <Link> import { Link } from 'react-router-dom'; const Navbar = () => ( <nav> <Link to="/">Home</Link> <Link to="/about">About</Link> </nav> );
// Example const Dashboard = () => ( <> <h2>Dashboard</h2> <Routes> <Route path="stats" element={<Stats />} /> <Route path="profile" element={<Profile />} /> </Routes> </> ); const App = () => ( <BrowserRouter> <Routes> <Route path="dashboard/*" element={<Dashboard />} /> </Routes> </BrowserRouter> );
const PrivateRoute = ({ children }) => { const auth = true; // Replace with auth logic return auth ? children : <Navigate to="/login" />; }; const App = () => ( <BrowserRouter> <Routes> <Route path="/login" element={<Login />} /> <Route path="/dashboard" element={ <PrivateRoute> <Dashboard /> </PrivateRoute> } /> </Routes> </BrowserRouter> );
// Next.js routing example // pages/index.js → route: / // pages/about.js → route: /about export default function Home() { return <h1>Welcome to Next.js!</h1>; } // Link example in Next.js import Link from 'next/link'; const Navbar = () => ( <nav> <Link href="/">Home</Link> <Link href="/about">About</Link> </nav> );
// Syntax using styled-components import styled from 'styled-components'; const Title = styled.h1` color: palevioletred; font-size: 24px; `; // Example 1 const App = () => <Title>Hello Styled Components!</Title>; // Example 2 const Button = styled.button` background: papayawhip; border: none; `; const App = () => <Button>Click Me</Button>;
// Example 1 import styled from 'styled-components'; const Wrapper = styled.div` padding: 1rem; background: #f0f0f0; `; const App = () => <Wrapper>Wrapped Content</Wrapper>; // Example 2 const Input = styled.input` border: 1px solid #ccc; padding: 8px; `; const App = () => <Input placeholder="Type here" />;
// Example 1 /** @jsxImportSource @emotion/react */ import { css } from '@emotion/react'; const style = css` color: hotpink; `; const App = () => <div css={style}>Styled by Emotion</div>; // Example 2 import styled from '@emotion/styled'; const Button = styled.button` background: lightblue; `; const App = () => <Button>Emotion Button</Button>;
// Example using react-jss import { createUseStyles } from 'react-jss'; const useStyles = createUseStyles({ myButton: { color: 'green', padding: '10px', }, }); const App = () => { const classes = useStyles(); return <button className={classes.myButton}>Click Me</button>; };
// styles.module.css .button { background-color: blue; color: white; } // Component.js import styles from './styles.module.css'; const App = () => <button className={styles.button}>CSS Module Button</button>;
// Example 1 const App = () => <div className="p-4 bg-red-200">Tailwind Styled</div>; // Example 2 const Button = () => <button className="bg-blue-500 text-white px-4 py-2">Click</button>;
// Example 1 const App = () => <h1 style={{ color: 'red', fontSize: '24px' }}>Inline Style</h1>; // Example 2 const Box = () => <div style={{ padding: '10px', backgroundColor: 'lightgray' }}>Box</div>;
import React, { useState } from 'react';
function ControlledForm() {
const [inputValue, setInputValue] = useState('');
const handleChange = (e) => {
setInputValue(e.target.value);
};
const handleSubmit = (e) => {
e.preventDefault();
alert(`Form submitted with value: ${inputValue}`);
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
value={inputValue}
onChange={handleChange}
/>
<button type="submit">Submit</button>
</form>
);
}
export default ControlledForm;
import React, { useRef } from 'react';
function UncontrolledForm() {
const inputRef = useRef();
const handleSubmit = (e) => {
e.preventDefault();
alert(`Form submitted with value: ${inputRef.current.value}`);
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
ref={inputRef}
/>
<button type="submit">Submit</button>
</form>
);
}
export default UncontrolledForm;
import React from 'react';
import { useForm } from 'react-hook-form';
function ReactHookFormExample() {
const { register, handleSubmit, formState: { errors } } = useForm();
const onSubmit = (data) => {
alert(`Form submitted: ${JSON.stringify(data)}`);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input
type="text"
{...register('name', { required: true })}
/>
{errors.name && <span>This field is required</span>}
<button type="submit">Submit</button>
</form>
);
}
export default ReactHookFormExample;
import React from 'react';
import { Formik, Field, Form } from 'formik';
function FormikExample() {
return (
<Formik
initialValues={{ name: '' }}
onSubmit={values => alert(`Form submitted: ${JSON.stringify(values)}`)}
>
<Form>
<Field name="name" />
<button type="submit">Submit</button>
</Form>
</Formik>
);
}
export default FormikExample;
import React from 'react';
import { Formik, Field, Form } from 'formik';
import * as Yup from 'yup';
const validationSchema = Yup.object({
name: Yup.string().required('Name is required')
});
function FormikWithYup() {
return (
<Formik
initialValues={{ name: '' }}
validationSchema={validationSchema}
onSubmit={values => alert(`Form submitted: ${JSON.stringify(values)}`)}
>
<Form>
<Field name="name" />
<button type="submit">Submit</button>
</Form>
</Formik>
);
}
export default FormikWithYup;
import React, { useState } from 'react';
function TextInput() {
const [value, setValue] = useState('');
const handleChange = (e) => {
setValue(e.target.value);
};
return (
<input
type="text"
value={value}
onChange={handleChange}
/>
);
}
export default TextInput;
import React, { useState } from 'react';
function CheckboxInput() {
const [checked, setChecked] = useState(false);
const handleChange = (e) => {
setChecked(e.target.checked);
};
return (
<input
type="checkbox"
checked={checked}
onChange={handleChange}
/>
);
}
export default CheckboxInput;
import React, { useState } from 'react';
function RadioButton() {
const [value, setValue] = useState('');
const handleChange = (e) => {
setValue(e.target.value);
};
return (
<div>
<input
type="radio"
name="gender"
value="male"
checked={value === 'male'}
onChange={handleChange}
/>
Male
<input
type="radio"
name="gender"
value="female"
checked={value === 'female'}
onChange={handleChange}
/>
Female
</div>
);
}
export default RadioButton;
import React, { useState } from 'react';
function SelectInput() {
const [value, setValue] = useState('');
const handleChange = (e) => {
setValue(e.target.value);
};
return (
<select value={value} onChange={handleChange}>
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="orange">Orange</option>
</select>
);
}
export default SelectInput;
import React, { useState } from 'react';
function SubmitForm() {
const [inputValue, setInputValue] = useState('');
const handleSubmit = (e) => {
e.preventDefault();
alert(`Form submitted with value: ${inputValue}`);
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
/>
<button type="submit">Submit</button>
</form>
);
}
export default SubmitForm;
import React, { useState, useEffect } from 'react';
function FetchExample() {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then(data => {
setData(data);
setLoading(false);
})
.catch(error => console.error('Error fetching data:', error));
}, []);
if (loading) return Loading...
;
return (
{data.map(post => (
- {post.title}
))}
);
}
export default FetchExample;
import React, { useState, useEffect } from 'react';
import axios from 'axios';
function AxiosExample() {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
axios.get('https://jsonplaceholder.typicode.com/posts')
.then(response => {
setData(response.data);
setLoading(false);
})
.catch(error => console.error('Error fetching data:', error));
}, []);
if (loading) return Loading...
;
return (
{data.map(post => (
- {post.title}
))}
);
}
export default AxiosExample;
import React, { useState, useEffect } from 'react';
function FetchOnRenderExample() {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then(data => {
setData(data);
setLoading(false);
})
.catch(error => console.error('Error fetching data:', error));
}, []); // Empty dependency array ensures this runs only once on mount
if (loading) return Loading...
;
return (
{data.map(post => (
- {post.title}
))}
);
}
export default FetchOnRenderExample;
import React, { Suspense } from 'react';
const fetchData = () => {
return fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json());
};
const Posts = React.lazy(() => fetchData());
function RenderAsYouFetch() {
return (
Loading...}>
);
}
export default RenderAsYouFetch;
import React from 'react';
import useSWR from 'swr';
const fetcher = (url) => fetch(url).then(res => res.json());
function SWRExample() {
const { data, error } = useSWR('https://jsonplaceholder.typicode.com/posts', fetcher);
if (error) return Error fetching data
;
if (!data) return Loading...
;
return (
{data.map(post => (
- {post.title}
))}
);
}
export default SWRExample;
import React from 'react';
import { useQuery } from 'react-query';
const fetchPosts = async () => {
const response = await fetch('https://jsonplaceholder.typicode.com/posts');
return response.json();
};
function ReactQueryExample() {
const { data, error, isLoading } = useQuery('posts', fetchPosts);
if (isLoading) return Loading...
;
if (error) return Error fetching data
;
return (
{data.map(post => (
- {post.title}
))}
);
}
export default ReactQueryExample;
import React, { useState, useEffect } from 'react';
function WebSocketExample() {
const [messages, setMessages] = useState([]);
const socket = new WebSocket('ws://example.com/socket');
useEffect(() => {
socket.onmessage = (event) => {
setMessages(prevMessages => [...prevMessages, event.data]);
};
return () => {
socket.close();
};
}, []);
return (
Messages:
{messages.map((message, index) => (
- {message}
))}
);
}
export default WebSocketExample;
<h1>10. Testing React Apps</h1> <h2>Unit Testing</h2> <h3>Using Jest</h3> <pre> <code> // Jest test for a simple component function import { render, screen } from '@testing-library/react'; import App from './App'; test('renders hello world', () => { render(<App />); const linkElement = screen.getByText(/hello world/i); expect(linkElement).toBeInTheDocument(); // Test if "hello world" is in the document }); </code> </pre> <h2>React Testing Library (render, fireEvent)</h2> <h3>Using render and fireEvent</h3> <pre> <code> import { render, screen, fireEvent } from '@testing-library/react'; import Button from './Button'; test('button click changes text', () => { render(<Button />); const button = screen.getByText(/click me/i); // Fire click event fireEvent.click(button); // Check if the text changes after the button click expect(screen.getByText(/button clicked/i)).toBeInTheDocument(); }); </code> </pre> <h2>Integration Testing</h2> <h3>Using Jest and React Testing Library for integration testing</h3> <pre> <code> import { render, screen, fireEvent } from '@testing-library/react'; import UserForm from './UserForm'; test('form submission works', () => { render(<UserForm />); // Find input and button elements const input = screen.getByLabelText(/name/i); const button = screen.getByRole('button', { name: /submit/i }); // Simulate user typing in input and submitting the form fireEvent.change(input, { target: { value: 'John Doe' } }); fireEvent.click(button); // Assert that the correct output is displayed expect(screen.getByText(/form submitted/i)).toBeInTheDocument(); }); </code> </pre> <h2>End-to-End (E2E) Testing</h2> <h3>Using Cypress</h3> <pre> <code> // Example of Cypress E2E test for a login form describe('Login Form', () => { it('submits the form successfully', () => { cy.visit('/login'); // Visit login page cy.get('input[name="username"]').type('user1'); // Type username cy.get('input[name="password"]').type('password123'); // Type password cy.get('button[type="submit"]').click(); // Click submit button cy.contains('Welcome, user1').should('be.visible'); // Verify welcome message }); }); </code> </pre> <h3>Using Playwright</h3> <pre> <code> // Playwright E2E test for the login form const { test, expect } = require('@playwright/test'); test('login form submission', async ({ page }) => { await page.goto('https://example.com/login'); // Go to login page await page.fill('input[name="username"]', 'user1'); // Fill username await page.fill('input[name="password"]', 'password123'); // Fill password await page.click('button[type="submit"]'); // Click submit button await expect(page).toContainText('Welcome, user1'); // Assert successful login }); </code> </pre> <h2>Mocking API Calls</h2> <h3>Using msw (Mock Service Worker)</h3> <pre> <code> import { render, screen, waitFor } from '@testing-library/react'; import { server, rest } from 'msw'; import { setupServer } from 'msw/node'; import App from './App'; // Set up mock server const mockServer = setupServer( rest.get('/api/user', (req, res, ctx) => { return res(ctx.json({ name: 'John Doe' })); }) ); beforeAll(() => mockServer.listen()); afterEach(() => mockServer.resetHandlers()); afterAll(() => mockServer.close()); test('displays user data from API', async () => { render(<App />); // Wait for API call to resolve and assert user data is displayed await waitFor(() => screen.getByText(/john doe/i)); expect(screen.getByText(/john doe/i)).toBeInTheDocument(); }); </code> </pre> <h3>Using jest.mock</h3> <pre> <code> import { render, screen } from '@testing-library/react'; import { fetchData } from './api'; // Assuming fetchData makes an API call import MyComponent from './MyComponent'; jest.mock('./api'); // Mock the api module test('fetches data and displays it', async () => { // Mock the implementation of fetchData fetchData.mockResolvedValue({ name: 'John Doe' }); render(<MyComponent />); // Wait for component to render data from the mocked API const nameElement = await screen.findByText(/john doe/i); expect(nameElement).toBeInTheDocument(); }); </code> </pre>
<h1>11. Server-Side Rendering (SSR) & Static Site Generation (SSG)</h1>
<h2>Next.js</h2>
<h3>getServerSideProps (SSR)</h3>>
<pre>
<code>
// Example of getServerSideProps for SSR in Next.js
export async function getServerSideProps(context) {
const res = await fetch('https://api.example.com/data');
const data = await res.json();
// Return data as props for the page
return { props: { data } };
}
export default function Page({ data }) {
return (
<div>
<h1>Server Side Rendered Page</h1>
<p>{data.message}</p> {/* Display data fetched from the server */}
</div>
);
}
</code>
</pre>
<h3>getStaticProps (SSG)</h3>
<pre>
<code>
// Example of getStaticProps for Static Site Generation (SSG) in Next.js
export async function getStaticProps() {
const res = await fetch('https://api.example.com/data');
const data = await res.json();
// Return data as props for the page
return { props: { data } };
}
export default function Page({ data }) {
return (
<div>
<h1>Static Site Generated Page</h1>
<p>{data.message}</p> {/* Display static data fetched at build time */}
</div>
);
}
</code>
</pre>
<h3>getStaticPaths (Dynamic SSG)</h3>
<pre>
<code>
// Example of getStaticPaths for dynamic SSG in Next.js
export async function getStaticPaths() {
const res = await fetch('https://api.example.com/posts');
const posts = await res.json();
// Generate paths for each post
const paths = posts.map(post => ({
params: { id: post.id.toString() }
}));
// Return paths and fallback behavior
return { paths, fallback: false };
}
export async function getStaticProps({ params }) {
const res = await fetch(`https://api.example.com/posts/${params.id}`);
const post = await res.json();
return { props: { post } };
}
export default function Post({ post }) {
return (
<div>
<h1>{post.title}</h1>
<p>{post.body}</p> {/* Display dynamic content based on the post */}
</div>
);
}
</code>
</pre>
<h2>Remix</h2>
<h3>Using Remix for SSR and SSG</h3>
<pre>
<code>
// Example of SSR in Remix
import { json, LoaderFunction } from 'remix';
export let loader: LoaderFunction = async () => {
const res = await fetch('https://api.example.com/data');
const data = await res.json();
return json(data); // Return data as JSON for SSR
};
export default function Page() {
const data = useLoaderData(); // Get the data from the loader
return (
<div>
<h1>SSR with Remix</h1>
<p>{data.message}</p> {/* Display data fetched from server-side loader */}
</div>
);
}
</code>
</pre>
<h2>Hydration & CSR vs. SSR Tradeoffs</h2>
<h3>Hydration Process</h3>
<pre>
<code>
// Hydration is the process where React takes over a server-rendered HTML page and "hydrates" it
// by attaching event listeners and converting it into a fully interactive page.
// Example of Hydration:
// 1. Initial HTML is sent from the server (SSR)
// 2. React re-renders the page on the client and attaches event handlers (Hydration)
</code>
</pre>
<h3>CSR (Client-Side Rendering) vs SSR (Server-Side Rendering)</h3>
<pre>
<code>
// CSR (Client-Side Rendering):
// - The browser fetches the HTML, CSS, and JavaScript and then renders the content.
// - Initially, the user sees a blank page, and the content is populated via JavaScript.
// - It results in slower initial page load but faster subsequent interactions.
// SSR (Server-Side Rendering):
// - The server renders the HTML and sends it to the browser.
// - The content is available to the user immediately, improving SEO and performance.
// - It can result in slower initial load time since rendering happens on the server.
// Tradeoff Example:
// - SSR is ideal for pages where SEO and fast first-load are important (e.g., blogs, landing pages).
// - CSR is better for interactive, highly dynamic apps where user experience matters more.
</code>
</pre>
// Example of typing props and state in a React component with TypeScript
interface PersonProps {
name: string;
age: number;
}
const Person: React.FC<PersonProps> = ({ name, age }) => {
// Typed props: `name` is a string, `age` is a number
return (
<div>
<h1>{name}</h1>
<p>Age: {age}</p>
</div>
);
};
const App = () => {
return <Person name="John Doe" age={30} />; // Using the typed Person component
};
// Example of using generics in React hooks with TypeScript
import { useState } from 'react';
const Counter = () => {
// Using generics to specify the type of state (`number`)
const [count, setCount] = useState<number>(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
};
export default Counter;
// Example of typing an event in TypeScript for an input change
import React, { useState } from 'react';
const InputForm = () => {
const [value, setValue] = useState<string>('');
const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
// `event` is typed as a ChangeEvent from an HTML input element
setValue(event.target.value);
};
return (
<div>
<input type="text" value={value} onChange={handleChange} />
<p>Current Value: {value}</p>
</div>
);
};
export default InputForm;
// Example of using React Context with TypeScript
import React, { createContext, useContext, useState } from 'react';
// Define the context type
interface UserContextType {
name: string;
setName: React.Dispatch<React.SetStateAction<string>>;
}
// Create a context with a default value
const UserContext = createContext<UserContextType | undefined>(undefined);
const UserProvider: React.FC = ({ children }) => {
const [name, setName] = useState<string>('John Doe');
return (
<UserContext.Provider value={{ name, setName }}>
{children}
</UserContext.Provider>
);
};
const UserProfile = () => {
const context = useContext(UserContext);
if (!context) {
throw new Error('UserProfile must be used within a UserProvider');
}
return (
<div>
<h1>User: {context.name}</h1>
<button onClick={() => context.setName('Jane Doe')}>Change Name</button>
</div>
);
};
const App = () => (
<UserProvider>
<UserProfile />
</UserProvider>
);
export default App;
<!-- Vite example setup for a React project -->
<!-- First, install Vite: -->
<!-- npm create vite@latest my-app --template react -->
<!-- Vite config (vite.config.ts): -->
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [react()],
});
<!-- Example Webpack setup for React project -->
<!-- Install dependencies: -->
<!-- npm install --save-dev webpack webpack-cli webpack-dev-server babel-loader @babel/preset-react react react-dom -->
<!-- Webpack config (webpack.config.js): -->
module.exports = {
entry: './src/index.js',
output: {
path: __dirname + '/dist',
filename: 'bundle.js',
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: 'babel-loader',
},
],
},
devServer: {
contentBase: './dist',
},
};
<!-- Example Parcel setup for a React project -->
<!-- Install Parcel globally: npm install -g parcel-bundler -->
<!-- Start a new React project: npm init -y && npm install react react-dom -->
<!-- Parcel will auto-configure, but you can create a .parcelrc file for custom configurations: -->
<!-- .parcelrc (optional): -->
{
"extends": "@parcel/config-default"
}
<!-- To start the development server: parcel index.html -->
<!-- Redux DevTools integration example -->
<!-- Install Redux and Redux DevTools: -->
<!-- npm install redux react-redux redux-devtools-extension -->
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
const initialState = { count: 0 };
const reducer = (state = initialState, action) => {
switch (action.type) {
case 'INCREMENT':
return { ...state, count: state.count + 1 };
default:
return state;
}
};
const store = createStore(reducer, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__());
const App = () => {
return (
<Provider store={store}>
<h1>Redux State: {store.getState().count}</h1>
</Provider>
);
};
<!-- React Query DevTools setup example -->
<!-- Install React Query and React Query DevTools: -->
<!-- npm install react-query @tanstack/react-query-devtools -->
import { useQuery, QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { ReactQueryDevtools } from '@tanstack/react-query-devtools';
const queryClient = new QueryClient();
const fetchData = async () => {
const res = await fetch('https://jsonplaceholder.typicode.com/posts');
return res.json();
};
const Posts = () => {
const { data, error, isLoading } = useQuery('posts', fetchData);
if (isLoading) return <div>Loading...</div>;
if (error) return <div>Error fetching data</div>;
return (
<div>
<h1>Posts:</h1>
<ul>
{data.map(post => (
<li key={post.id}>{post.title}</li>
))}
</ul>
</div>
);
};
const App = () => (
<QueryClientProvider client={queryClient}>
<Posts />
<ReactQueryDevtools initialIsOpen={false} />
</QueryClientProvider>
);
<!-- Setting up ESLint for a React project -->
<!-- Install ESLint and React plugin: -->
<!-- npm install eslint eslint-plugin-react -->
<!-- ESLint config (.eslintrc.js): -->
module.exports = {
parser: '@babel/eslint-parser',
extends: ['eslint:recommended', 'plugin:react/recommended'],
parserOptions: {
ecmaVersion: 2020,
sourceType: 'module',
},
rules: {
'react/prop-types': 'off',
},
};
<!-- Setting up Prettier for formatting -->
<!-- Install Prettier: -->
<!-- npm install --save-dev prettier -->
<!-- .prettierrc config: -->
{
"semi": false,
"singleQuote": true,
"tabWidth": 2,
"trailingComma": "es5"
}
<!-- To run Prettier: npx prettier --write . -->
<!-- Installing React DevTools for debugging -->
<!-- React DevTools are installed as a browser extension. -->
<!-- After installing, you can open the React tab in the browser's Developer Tools. -->
<!-- You can inspect the component tree, state, and props directly through React DevTools. -->
<!-- Using React Profiler to measure performance -->
<!-- Wrap your components with React Profiler to measure their render times. -->
import React, { Profiler } from 'react';
const App = () => {
const onRenderCallback = (id, phase, actualDuration) => {
console.log(`Component ${id} rendered in ${actualDuration}ms during ${phase}`);
};
return (
<Profiler id="App" onRender={onRenderCallback}>
<h1>Hello World!</h1>
</Profiler>
);
};
export default App;
// React Fiber is a complete rewrite of React's core algorithm
// It allows React to break rendering work into chunks and prioritize updates.
// This enables smoother, non-blocking rendering, especially for complex UIs.
// Example of a component rendering without blocking the UI:
const App = () => {
const [counter, setCounter] = useState(0);
// Simulate complex rendering task
useEffect(() => {
const timer = setInterval(() => {
setCounter((prev) => prev + 1);
}, 1000);
return () => clearInterval(timer);
}, []);
return (
<div>
<h1>Counter: {counter}</h1>
<p>React Fiber allows for non-blocking updates and smoother transitions.</p>
</div>
);
};
// startTransition is a feature in Concurrent Mode that allows you to mark updates as non-urgent
// This helps in preventing blocking UI updates, improving responsiveness.
const App = () => {
const [count, setCount] = useState(0);
const [isPending, startTransition] = useTransition();
const handleClick = () => {
startTransition(() => {
setCount(count + 1);
});
};
return (
<div>
<h1>Count: {count}</h1>
<button onClick={handleClick}>
Increment
</button>
{isPending && <p>Loading...</p>}
</div>
);
};
// useDeferredValue allows you to defer rendering of a non-urgent update.
// It helps with scenarios where you don't want to block the user interface with updates.
const App = () => {
const [input, setInput] = useState('');
const deferredInput = useDeferredValue(input);
return (
<div>
<input
type="text"
value={input}
onChange={(e) => setInput(e.target.value)}
/>
<p>Deferred Input: {deferredInput}</p>
</div>
);
};
// React Portals allow rendering components outside their parent component's DOM hierarchy.
// This is useful for rendering modals, tooltips, and other UI elements that need to overlay the app.
const Modal = ({ children }) => {
return ReactDOM.createPortal(
<div style={{ position: 'fixed', top: '20px', left: '50%', transform: 'translateX(-50%)' }}>
{children}
</div>,
document.body
);
};
const App = () => {
const [showModal, setShowModal] = useState(false);
return (
<div>
<button onClick={() => setShowModal(true)}>Show Modal</button>
{showModal && (
<Modal>
<div>
<h1>Modal Content</h1>
<button onClick={() => setShowModal(false)}>Close</button>
</div>
</Modal>
)}
</div>
);
};
// Web Components are reusable custom elements that work across different frameworks, including React.
// React can render and interact with Web Components using the `dangerouslySetInnerHTML` attribute or refs.
class MyButton extends HTMLElement {
connectedCallback() {
this.innerHTML = '<button>Click Me</button>';
}
}
customElements.define('my-button', MyButton);
const App = () => {
return (
<div>
<my-button></my-button>
</div>
);
};
// react-i18next is a popular library for handling internationalization (i18n) in React apps.
// It provides hooks for translating text and switching languages.
// Install dependencies:
// npm install react-i18next i18next
import { useTranslation } from 'react-i18next';
const App = () => {
const { t, i18n } = useTranslation();
return (
<div>
<h1>{t('hello')}</h1>
<button onClick={() => i18n.changeLanguage('fr')}>Switch to French</button>
</div>
);
};
// i18n.js config:
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
i18n.use(initReactI18next).init({
resources: {
en: {
translation: {
hello: 'Hello',
},
},
fr: {
translation: {
hello: 'Bonjour',
},
},
},
lng: 'en', // Default language
interpolation: {
escapeValue: false,
},
});
// React Spring is a library that helps in creating physics-based animations.
// It makes animations more realistic with spring physics.
import { useSpring, animated } from 'react-spring';
const App = () => {
const props = useSpring({
to: { opacity: 1, transform: 'scale(1)' },
from: { opacity: 0, transform: 'scale(0.5)' },
reset: true,
});
return (
<animated.div style={props}>
<h1>Physics-based Animation with React Spring</h1>
</animated.div>
);
};
// The animation starts with the div scaled down and fully transparent,
// then scales up and fades in due to the physics-based animation effect.
// Framer Motion is a library for declarative animations in React.
// It allows creating complex animations with a simple API.
import { motion } from 'framer-motion';
const App = () => {
return (
<motion.div
animate={{ rotate: 360 }}
transition={{ duration: 2 }}>
<h1>Declarative Animation with Framer Motion</h1>
</motion.div>
);
};
// This example rotates the div by 360 degrees over 2 seconds, using a declarative approach.
// Framer Motion handles the animation automatically, making it easy to create complex animations.
// CSS Transitions and Keyframes can also be used in React to create animations.
// Here's an example of using CSS transitions to animate a component.
const App = () => {
return (
<div className="animated-div">
<h1>CSS Transition in React</h1>
</div>
);
};
// In the CSS file:
// .animated-div {
// transition: transform 0.5s ease-in-out;
// transform: scale(1);
// }
// .animated-div:hover {
// transform: scale(1.5);
// }
// When you hover over the div, it scales up smoothly.
// React Transition Group is a library for handling enter/exit animations for components.
// It allows you to add transitions when elements enter or exit the DOM.
import { CSSTransition } from 'react-transition-group';
import './App.css'; // Make sure to create relevant CSS for transition
const App = () => {
const [inProp, setInProp] = useState(false);
return (
<div>
<button onClick={() => setInProp(!inProp)}>
Toggle Animation
</button>
<CSSTransition
in={inProp}
timeout={500}
classNames="fade"
unmountOnExit
>
<div className="box">I will fade in and out</div>
</CSSTransition>
</div>
);
};
// CSS (App.css):
// .fade-enter {
// opacity: 0;
// }
// .fade-enter-active {
// opacity: 1;
// transition: opacity 500ms;
// }
// .fade-exit {
// opacity: 1;
// }
// .fade-exit-active {
// opacity: 0;
// transition: opacity 500ms;
// }
// The `CSSTransition` component from React Transition Group animates the entry and exit of a component.
// The `box` will fade in and out based on the `inProp` state.
React Spring provides a physics-based animation system that mimics real-world physics like springs. It allows smoother, more natural animations by animating based on a spring model.
The example animates the opacity and scale of a div using useSpring
, which begins with a scale of 0.5
and opacity 0
and animates to scale(1)
and opacity(1)
.
Framer Motion is a declarative animation library for React. Instead of manually controlling animation frames,
you describe the animation using simple properties like animate
and transition
.
The example shows a div
rotating 360
degrees over 2
seconds with simple declarative syntax, making it very easy to implement animations.
CSS Transitions and Keyframes can also be used for animations in React components. This approach doesn't require external libraries and leverages the native browser support for CSS animations.
The example uses CSS to animate the scale of a div
when it's hovered over, smoothly transitioning from scale(1)
to scale(1.5)
.
React Transition Group is a powerful library for handling component lifecycle transitions (entering and exiting the DOM). It provides hooks to define and control enter/exit animations.
The example demonstrates how to toggle visibility of a div
with a fade-in and fade-out effect using the CSSTransition
component,
where the component fades in/out depending on the inProp
state.
Syntax:
// webpack.config.js of the host app
module.exports = {
plugins: [
new ModuleFederationPlugin({
name: 'hostApp',
remotes: {
microApp: 'microApp@http://localhost:3001/remoteEntry.js',
},
}),
],
};
// webpack.config.js of the micro app
module.exports = {
plugins: [
new ModuleFederationPlugin({
name: 'microApp',
exposes: {
'./Button': './src/Button',
},
}),
],
};
Example:
// Host App imports Button from Micro App
import React from 'react';
const Button = React.lazy(() => import('microApp/Button'));
function App() {
return (
<div>
<h1>Host App</h1>
<React.Suspense fallback=<div>Loading...</div>>
<Button />
</React.Suspense>
</div>
);
}
Output:
The host app loads the Button component from the micro app. When the host app is loaded, the micro app is fetched dynamically using Module Federation, and the Button component is displayed after the lazy load completes.
Syntax:
// Import necessary modules
import { registerApplication, start } from 'single-spa';
// Registering the React app as a microfrontend
registerApplication(
'reactApp',
() => import('./ReactApp'),
(location) => location.pathname.startsWith('/react')
);
// Start single-spa
start();
Example:
// ReactApp component that will be a microfrontend
import React from 'react';
const ReactApp = () => {
return (
<div>
<h1>React Micro App</h1>
</div>
);
};
export default ReactApp;
Output:
The `single-spa` library will load the React app as a microfrontend when the user navigates to the path `/react`. The React app will be rendered independently alongside other frameworks or microfrontends.
Syntax:
// React.lazy() to lazy load a component
const LazyComponent = React.lazy(() => import('./LazyComponent'));
function App() {
return (
<div>
<h1>App with Lazy-loaded Micro-App</h1>
<React.Suspense fallback=<div>Loading...</div>>
<LazyComponent />
</React.Suspense>
</div>
);
}
Example:
// LazyComponent.js
import React from 'react';
const LazyComponent = () => {
return <div>This is a lazily loaded component!</div>;
};
export default LazyComponent;
Output:
The `LazyComponent` will be loaded only when it's needed. Initially, the "Loading..." message is shown until the component is loaded. This helps in reducing the initial load time of the app.
Syntax:
// webpack.config.js configuration for workbox-webpack-plugin
const WorkboxPlugin = require('workbox-webpack-plugin');
module.exports = {
plugins: [
new WorkboxPlugin.GenerateSW({
clientsClaim: true,
skipWaiting: true,
}),
],
};
Example:
// Service worker registration in React app (service-worker.js)
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker
.register('/service-worker.js')
.then((registration) => {
console.log('Service Worker registered with scope:', registration.scope);
})
.catch((error) => {
console.log('Service Worker registration failed:', error);
});
});
}
Output:
This example demonstrates how to use the `workbox-webpack-plugin` to generate a service worker for the React app during the Webpack build process. The service worker is then registered in the React app to enable caching and offline functionality. When the app is loaded, the service worker is activated and can serve content offline or cache assets for future use.
Syntax:
// Caching strategies using Workbox for offline-first approach
workbox.routing.registerRoute(
new RegExp('.*\.html$'),
new workbox.strategies.NetworkFirst({
cacheName: 'html-cache',
})
);
Example:
// Implementing Offline-first with service worker caching strategy
workbox.routing.registerRoute(
new RegExp('/assets/.*'),
new workbox.strategies.CacheFirst({
cacheName: 'assets-cache',
})
);
Output:
This example shows an offline-first strategy where assets are cached using `CacheFirst` strategy. When the user accesses the app, the service worker will try to serve the assets from the cache first and fall back to the network if not found, ensuring the app works offline.
Syntax:
// manifest.json file for PWA
{
"short_name": "ReactApp",
"name": "My Progressive Web App",
"icons": [
{
"src": "icons/icon-192x192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "icons/icon-512x512.png",
"sizes": "512x512",
"type": "image/png"
}
],
"start_url": "/?source=pwa",
"display": "standalone",
"background_color": "#ffffff",
"theme_color": "#4CAF50"
}
Example:
// Link to manifest.json in the HTML file
Output:
This example shows a `manifest.json` file, which contains metadata about the PWA, including the app's name, icons, start URL, and theme color. This information allows the app to be added to the home screen of mobile devices, providing a native-like experience. The manifest is linked to the HTML file using a `` tag.
Syntax:
// Background sync example using workbox
workbox.routing.registerRoute(
new RegExp('.*\/api\/.*'),
new workbox.strategies.NetworkOnly({
plugins: [
new workbox.backgroundSync.Plugin('api-queue', {
maxRetentionTime: 24 * 60, // Retry for 24 hours
}),
],
})
);
Example:
// Example of background sync in the service worker
self.addEventListener('sync', (event) => {
if (event.tag === 'syncData') {
event.waitUntil(fetchDataAndUpdateDatabase());
}
});
Output:
This example demonstrates background sync with `workbox` where API requests are queued and retried when the network is back online. The service worker listens for the `sync` event and retries the failed requests to ensure data consistency even when offline.
This part explains how to use the workbox-webpack-plugin in Webpack to generate a service worker, which enables caching and offline functionality in a React app. The service worker is registered in the React app, allowing offline support and caching of assets.
// Step 1: Install Workbox plugin
npm install workbox-webpack-plugin --save-dev
// Step 2: Modify webpack.config.js to include Workbox plugin
const WorkboxPlugin = require('workbox-webpack-plugin');
module.exports = {
// other config...
plugins: [
new WorkboxPlugin.GenerateSW({
clientsClaim: true,
skipWaiting: true,
}),
],
};
The example shows how to implement offline-first caching strategies using Workbox. The CacheFirst strategy is used for assets, ensuring that the app can still work offline by serving cached resources when the user is offline.
// Example of implementing CacheFirst strategy
workbox.routing.registerRoute(
({ request }) => request.destination === 'image',
new workbox.strategies.CacheFirst({
cacheName: 'images-cache',
plugins: [
new workbox.expiration.Plugin({
maxEntries: 10,
maxAgeSeconds: 24 * 60 * 60, // 1 day
}),
],
})
);
The manifest file (manifest.json
) contains metadata for the PWA, including app name, icons, and theme color. This file is essential for enabling the PWA to be installed on devices, providing a native-like experience. The manifest is linked in the HTML file with a <link>
tag.
// Example manifest.json
{
"name": "My PWA App",
"short_name": "PWA",
"start_url": ".",
"display": "standalone",
"background_color": "#ffffff",
"theme_color": "#4CAF50",
"icons": [
{
"src": "icons/manifest-icon-192.maskable.png",
"sizes": "192x192",
"type": "image/png"
}
]
}
This part shows how to implement background sync using Workbox, allowing failed API requests to be queued and retried when the network is back online. The sync event listens for background sync tasks and processes them when possible.
// Example of background sync using Workbox
workbox.routing.registerRoute(
({ url }) => url.origin === 'https://api.example.com',
new workbox.strategies.NetworkOnly({
plugins: [
new workbox.backgroundSync.Plugin('api-queue', {
maxRetentionTime: 24 * 60 // Retry for up to 24 hours
}),
],
})
);
With this setup, failed API requests are stored in the background sync queue and retried when the network is back online, ensuring that offline users still have a smooth experience.
Syntax:
// Example of Core Components in React Native
import React from 'react';
import { View, Text, FlatList } from 'react-native';
const data = [
{ id: '1', name: 'John Doe' },
{ id: '2', name: 'Jane Smith' },
];
const App = () => (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text>Hello, React Native!</Text>
<FlatList
data={data}
renderItem={({ item }) => <Text>{item.name}</Text>}
keyExtractor={(item) => item.id}
/>
</View>
);
export default App;
Example:
// The app displays a simple message and a list of names using core components:
// View, Text, and FlatList
Output:
This example shows how to use React Native's core components like `View`, `Text`, and `FlatList` to render a basic app. The `View` component serves as a container, and `Text` is used to display text. `FlatList` is used to display a list of items efficiently.
Syntax:
// Example of bridging a native module in React Native
import { NativeModules } from 'react-native';
const { MyCustomModule } = NativeModules;
MyCustomModule.customFunction()
.then((result) => console.log(result))
.catch((error) => console.error(error));
Example:
// This shows how to use a native module in React Native to call a custom function.
Output:
This example demonstrates how React Native can communicate with native modules. By using `NativeModules`, we can call platform-specific functions written in Java/Kotlin (Android) or Objective-C/Swift (iOS) from JavaScript.
Syntax:
// Example of setting up an Expo project (managed workflow)
npx create-expo-app MyApp
// Example of setting up a Bare React Native project
npx react-native init MyApp
Example:
// Expo is a framework that offers a set of preconfigured tools for building React Native apps,
// while Bare workflow gives you more control over native dependencies.
Output:
Expo is great for quick development as it handles all the setup and configuration. In contrast, Bare workflow (using React Native CLI) gives you full control over the native part of the app, such as linking native dependencies and modifying Android/iOS code directly.
Syntax:
// Example of shared logic between React Web and React Native
import React from 'react';
const Button = ({ onPress }) => (
<button onClick={onPress}>Click Me</button>
);
export default Button;
Example:
// The Button component can be used in both React Web and React Native
// For React Native, you can import TouchableOpacity instead of <button>.
Output:
This example demonstrates how you can share components between React Web and React Native. The `Button` component can be reused on both platforms with minor adjustments (e.g., replacing `button` with `TouchableOpacity` in React Native) to ensure compatibility.
This section explains how to use React Native's core components, such as View for layout, Text for displaying text, and FlatList for rendering large lists efficiently.
// Example of using View, Text, and FlatList in React Native
import React from 'react';
import { View, Text, FlatList } from 'react-native';
const App = () => {
const data = [
{ id: '1', title: 'Item 1' },
{ id: '2', title: 'Item 2' },
{ id: '3', title: 'Item 3' },
];
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text>Hello, React Native!</Text>
<FlatList
data={data}
renderItem={({ item }) => <Text>{item.title}</Text>}
keyExtractor={(item) => item.id}
/>
</View>
);
};
export default App;
This section covers how React Native can interact with native code using "bridging." It allows you to call native modules (written in Java/Kotlin for Android or Objective-C/Swift for iOS) from JavaScript.
// Example of bridging a native module in React Native (Android)
import { NativeModules } from 'react-native';
const { CustomModule } = NativeModules;
CustomModule.someMethod('hello', (response) => {
console.log(response); // Handle the response from the native module
});
// Java code for CustomModule.java
package com.yourproject;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
public class CustomModule extends ReactContextBaseJavaModule {
CustomModule(ReactApplicationContext reactContext) {
super(reactContext);
}
@Override
public String getName() {
return "CustomModule";
}
@ReactMethod
public void someMethod(String message, Callback callback) {
// Handle the logic and return data to JS
callback.invoke("Native response: " + message);
}
}
This section explains the difference between using the Expo managed workflow, which simplifies the setup and development process, and the Bare workflow, where you have full control over native code and dependencies.
The Expo managed workflow provides a simplified environment with pre-configured tools and libraries. It allows you to build and run React Native apps without dealing with native code, but you are limited in terms of native customizations.
// Example: Using Expo Managed Workflow
import React from 'react';
import { Button } from 'react-native';
const App = () => {
return <Button title="Click Me" onPress={() => alert('Hello from Expo!')} />;
};
export default App;
The Bare workflow allows full control over the native code and dependencies. You are responsible for configuring the native environment, which is ideal for projects requiring custom native modules or deeper integration with the device’s features.
// Example: Using Bare Workflow with custom native modules
import React from 'react';
import { Button } from 'react-native';
import { NativeModules } from 'react-native';
const { CustomModule } = NativeModules;
const App = () => {
return (
<Button
title="Call Native Code"
onPress={() => CustomModule.someMethod('Hello')}
/>
);
};
export default App;
This section demonstrates how components and logic can be shared between React Web and React Native, with small adjustments for platform-specific components (like using TouchableOpacity in React Native instead of button).
// Example of shared logic with React Web and React Native
import React from 'react';
import { Platform } from 'react-native';
import { Button as WebButton } from 'react-web';
import { TouchableOpacity } from 'react-native';
const Button = Platform.OS === 'web' ? WebButton : TouchableOpacity;
const App = () => {
return <Button onPress={() => alert('Button pressed!')}>Press Me</Button>;
};
export default App;
Syntax:
// Example of integrating a WASM module in React using wasm-pack
import React, { useEffect, useState } from 'react';
const wasmModule = import('path/to/your/wasm/pkg'); // Replace with the path to your wasm module
const App = () => {
const [wasmReady, setWasmReady] = useState(false);
useEffect(() => {
wasmModule.then((wasm) => {
setWasmReady(true);
wasm.yourFunction(); // Call a function from your WASM module
});
}, []);
return (
{wasmReady ? (
<p>WASM module is ready!</p>
) : (
<p>Loading WASM module...</p>
)}
);
};
export default App;
Example:
// This example imports a WASM module and waits for it to load.
// Once loaded, it calls a function from the WASM module and displays a loading message until ready.
Output:
This example demonstrates how to load and use a WASM module in a React application using the wasm-pack
package. The useEffect
hook is used to load the WASM module asynchronously, and once it's ready, a function from the WASM module is invoked, and the UI displays a message indicating the module's readiness.
Syntax:
// Example of using WASM for performance-intensive tasks like image processing
const processImageWithWASM = async (imageData) => {
const wasm = await import('path/to/your/imageProcessingWasm/pkg');
return wasm.processImage(imageData); // Call a WASM function to process the image
};
const App = () => {
const handleImageUpload = (event) => {
const imageData = event.target.files[0];
processImageWithWASM(imageData).then((processedImage) => {
console.log(processedImage);
});
};
return (
<div>
<input type="file" onChange={handleImageUpload} />
</div>
);
};
export default App;
Example:
// In this example, an image is uploaded, and the image data is passed to a WASM module
// for processing. The `processImage` function is called asynchronously, leveraging WASM's
// performance capabilities for tasks like image processing.
Output:
This example demonstrates using WASM for performance-intensive tasks like image or video processing. By offloading the processing to WASM, which can run natively in the browser at near-native speeds, React can handle large computations more efficiently without blocking the main thread.
Syntax:
// Example of using Rust with WASM in React
// Rust code should be compiled to WASM using wasm-pack
import React, { useEffect, useState } from 'react';
const wasmModule = import('path/to/your/rustWasm/pkg'); // Path to the compiled Rust WASM module
const App = () => {
const [result, setResult] = useState(null);
useEffect(() => {
wasmModule.then((wasm) => {
const rustFunction = wasm.rustFunction(); // Call the function from the Rust WASM module
setResult(rustFunction);
});
}, []);
return (
<div>
{result ? <p>Result from Rust WASM: {result}</p> : <p>Loading Rust WASM...</p>}
</div>
);
};
export default App;
Example:
// This example demonstrates calling a function from a Rust module compiled into WASM
// using `wasm-pack` to interact with a React app.
Output:
This example demonstrates using Rust alongside React through WebAssembly. Rust code is compiled into a WASM module using wasm-pack
, and then it is imported and used in a React app. The useEffect
hook ensures that the Rust function is called when the component is mounted, providing an efficient way to run performance-sensitive tasks using Rust's low-level performance characteristics directly within a React app.
Syntax:
// Example of integrating OpenAI's GPT model in a React app
import React, { useState } from 'react';
const App = () => {
const [response, setResponse] = useState("");
const [query, setQuery] = useState("");
const handleSubmit = async () => {
const res = await fetch('https://api.openai.com/v1/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer YOUR_OPENAI_API_KEY`,
},
body: JSON.stringify({
model: "text-davinci-003",
prompt: query,
max_tokens: 50
}),
});
const data = await res.json();
setResponse(data.choices[0].text);
};
return (
<div>
<input
type="text"
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Ask something..."
/>
<button onClick={handleSubmit}>Ask</button>
<p>Response: {response}</p>
</div>
);
};
export default App;
Example:
// This example demonstrates how to use OpenAI's GPT API to create an LLM-powered UI
// Users can input a query, and the app sends the query to OpenAI's API to generate a response.
Output:
This example creates an interactive user interface where users can type a query. Once the query is submitted, the application makes an API request to OpenAI's GPT model, which processes the query and returns a response. This shows how to build a React-based UI powered by large language models (LLMs).
Syntax:
// Example of using React Flow to create an AI pipeline interface
import React from 'react';
import ReactFlow, { MiniMap, Controls } from 'react-flow-renderer';
const elements = [
{ id: '1', type: 'input', data: { label: 'Input Node' }, position: { x: 0, y: 0 } },
{ id: '2', data: { label: 'AI Model Node' }, position: { x: 150, y: 0 } },
{ id: '3', type: 'output', data: { label: 'Output Node' }, position: { x: 300, y: 0 } },
{ id: 'e1-2', source: '1', target: '2', animated: true },
{ id: 'e2-3', source: '2', target: '3', animated: true },
];
const App = () => {
return (
<div style={{ height: '100vh' }}>
<ReactFlow elements={elements}>
<MiniMap />
<Controls />
</ReactFlow>
</div>
);
};
export default App;
Example:
// In this example, we use React Flow to create a visual AI pipeline
// consisting of input, AI model, and output nodes. The connections
// between the nodes represent the data flow in the AI pipeline.
Output:
This example shows how React Flow can be used to create AI pipeline visualizations in a React app. The nodes represent different stages of an AI process (e.g., data input, AI model, output), and the edges between them represent the flow of data. This allows users to build and visualize AI workflows directly in a React-based UI.
Syntax:
// Example of integrating a real-time AI chatbot using WebSockets
import React, { useState, useEffect } from 'react';
const ChatApp = () => {
const [messages, setMessages] = useState([]);
const [input, setInput] = useState("");
useEffect(() => {
const socket = new WebSocket('wss://your-websocket-url');
socket.onmessage = (event) => {
const data = JSON.parse(event.data);
setMessages((prevMessages) => [...prevMessages, data.message]);
};
return () => socket.close();
}, []);
const sendMessage = () => {
const socket = new WebSocket('wss://your-websocket-url');
socket.onopen = () => {
socket.send(JSON.stringify({ message: input }));
setInput("");
};
};
return (
<div>
<div>
{messages.map((msg, idx) => (
<p key={idx}>{msg}</p>
))}
</div>
<input
type="text"
value={input}
onChange={(e) => setInput(e.target.value)}
placeholder="Type your message..."
/>
<button onClick={sendMessage}>Send</button>
</div>
);
};
export default ChatApp;
Example:
// This example shows how to implement a real-time AI chatbot with WebSockets.
// Messages are sent and received in real-time, simulating an AI-powered feedback system.
Output:
This example demonstrates how to create a real-time AI chatbot that communicates via WebSockets. The application sends user input to a WebSocket server and listens for responses, allowing users to interact with the AI in real-time. This integration can be used for applications such as chatbots or recommendation engines, where immediate feedback is required.
Syntax:
// Example of a simple React Server Component (RSC) with Next.js 13
// Create a server-side rendered component in Next.js 13+ (Server Component)
import React from 'react';
// This is a React Server Component
export default function ServerComponent() {
return (
Server-Side Content
This content is rendered on the server.
);
}
Example:
// In this example, the ServerComponent is rendered on the server side.
// React Server Components allow rendering parts of your app on the server
// to improve performance by reducing JavaScript on the client.
Output:
The component is rendered server-side, meaning it will be sent to the client as static HTML, which can improve load time by reducing the amount of JavaScript running in the browser. This approach can improve SEO and reduce client-side JavaScript size.
Syntax:
// Example of Islands Architecture in Astro with React
// Create a simple component in Astro
import { Component } from 'astro';
// React component that will be "hydrated" (interactive) on the client-side
export default function InteractiveComponent() {
return (
);
}
Example:
// In this example, we create an interactive component using Astro and React.
// Astro only sends HTML to the browser initially, and the React component is hydrated (made interactive)
// when the user interacts with it. This is known as Islands Architecture.
Output:
Astro generates static HTML on the server, and only the interactive parts (React components) are hydrated on the client-side when the user interacts with them. This allows a mix of static content and dynamic, interactive components without the need to load large amounts of JavaScript upfront.
Syntax:
// Example of edge rendering using Cloudflare Workers
// This is a basic Cloudflare Worker setup to render content at the edge
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request));
});
async function handleRequest(request) {
const url = new URL(request.url);
const html = `
Edge Rendered Content
This content is rendered at the edge, closer to the user!
`;
return new Response(html, { headers: { 'Content-Type': 'text/html' } });
}
Example:
// In this example, Cloudflare Workers runs code at the edge of the network,
// meaning it executes closer to the user to improve performance by reducing latency.
// The HTML response is generated on the edge server, reducing the time it takes to deliver content.
Output:
Edge rendering allows for faster content delivery by serving static HTML from servers located closer to the user. Cloudflare Workers and Vercel's Edge Functions let you render content at the edge, improving response times and reducing the load on central servers.