Lin / docu_code /react_handling_cookies.txt
Zelyanoth's picture
fff
25f22bf
raw
history blame
52.7 kB
========================
CODE SNIPPETS
========================
TITLE: React Context API: Passing Dynamic Objects and Functions
DESCRIPTION: This snippet illustrates passing a dynamic JavaScript object, containing both state (`currentUser`) and a function (`login`), as a context value. It highlights a common performance pitfall where creating a new object/function on every render causes unnecessary re-renders of consuming components, even if the underlying data hasn't changed.
SOURCE: https://react.dev/reference/react/useContext
LANGUAGE: JavaScript
CODE:
```
function MyApp() {
const [currentUser, setCurrentUser] = useState(null);
function login(response) {
storeCredentials(response.credentials);
setCurrentUser(response.user);
}
return (
<AuthContext value={{ currentUser, login }}>
<Page />
</AuthContext>
);
}
```
----------------------------------------
TITLE: Preventing Token Exposure with globalThis Lifetime
DESCRIPTION: Illustrates how to use `experimental_taintUniqueValue` to protect a sensitive value, such as a user password, by tainting it for the entire application's lifetime using `globalThis`.
SOURCE: https://react.dev/reference/react/experimental_taintUniqueValue
LANGUAGE: JavaScript
CODE:
```
import {experimental_taintUniqueValue} from 'react';
experimental_taintUniqueValue(
'Do not pass a user password to the client.',
globalThis,
process.env.SECRET_KEY
);
```
----------------------------------------
TITLE: Securing getUser with experimental_taintObjectReference
DESCRIPTION: This updated version of the `getUser` function demonstrates how to use React's `experimental_taintObjectReference` to prevent sensitive data leaks. By 'tainting' the user object, an error will be thrown if the entire object is inadvertently passed to a client component, enforcing data security.
SOURCE: https://react.dev/reference/react/experimental_taintObjectReference
LANGUAGE: JavaScript
CODE:
```
// api.js
import {experimental_taintObjectReference} from 'react';
export async function getUser(id) {
const user = await db`SELECT * FROM users WHERE id = ${id}`;
experimental_taintObjectReference(
'Do not pass the entire user object to the client. ' +
'Instead, pick off the specific properties you need for this use case.',
user,
);
return user;
}
```
----------------------------------------
TITLE: React experimental_taintUniqueValue API Reference
DESCRIPTION: Documents the experimental `taintUniqueValue` API, which is designed to prevent sensitive, unique values (like passwords or tokens) from being inadvertently passed from Server Components to Client Components. This API is currently only available in experimental React versions and should not be used in production environments. It is specifically for use within React Server Components.
SOURCE: https://react.dev/reference/react/experimental_taintUniqueValue
LANGUAGE: APIDOC
CODE:
```
taintUniqueValue(message, lifetime, value)
Description:
This API prevents unique values from being passed to Client Components, such as passwords, keys, or tokens. It is an experimental feature and is not available in stable React versions. It should only be used within React Server Components.
Parameters:
- message: (string) An error message that will be thrown if the tainted value is accessed in a Client Component.
- lifetime: (string) Specifies the lifetime of the taint. The exact values and their meanings are part of the experimental API and typically relate to the scope of the taint (e.g., 'request', 'session').
- value: (any) The unique value to be tainted and prevented from being passed to Client Components.
Usage Notes:
- To use this API, React packages must be upgraded to the most recent experimental version (e.g., `react@experimental`, `react-dom@experimental`).
- Experimental versions may contain bugs and are not suitable for production.
- For preventing objects containing sensitive data, refer to `taintObjectReference`.
Example Usage:
// Prevent a token from being passed to Client Components
// (Specific code example not provided in source, but conceptual usage is for securing tokens)
```
----------------------------------------
TITLE: Secure Server-Side API Fetch with `server-only`
DESCRIPTION: This snippet demonstrates the recommended secure practice for handling sensitive data. By importing `server-only`, this `fetchAPI` helper function is guaranteed to only run on the server. It directly accesses `process.env.API_PASSWORD` for authorization, ensuring the secret never leaves the server environment and is not bundled with client-side code.
SOURCE: https://react.dev/reference/react/experimental_taintUniqueValue
LANGUAGE: JavaScript
CODE:
```
import "server-only";
export function fetchAPI(url) {
const headers = { Authorization: process.env.API_PASSWORD };
return fetch(url, { headers });
}
```
----------------------------------------
TITLE: Client Component Using Leaked Secret for Authorization
DESCRIPTION: This Client Component (`Overview`) receives a `password` prop, which, if leaked from a Server Component, is then used directly in an `Authorization` header for a `fetch` request. This illustrates the consequence of the previous insecure pattern, where the client-side code now has access to and uses the sensitive secret.
SOURCE: https://react.dev/reference/react/experimental_taintUniqueValue
LANGUAGE: JavaScript
CODE:
```
"use client";
import {useEffect} from '...'
export async function Overview({ password }) {
useEffect(() => {
const headers = { Authorization: password };
fetch(url, { headers }).then(...);
}, [password]);
...
```
----------------------------------------
TITLE: Progressive Enhancement with useActionState Permalink
DESCRIPTION: This example illustrates how to enable progressive enhancement for forms using `useActionState` by providing a permalink as the third argument. If the form is submitted before the JavaScript bundle loads, React will automatically redirect to the specified URL, ensuring basic functionality even without full client-side hydration.
SOURCE: https://react.dev/reference/rsc/server-functions
LANGUAGE: javascript
CODE:
```
"use client";
import {updateName} from './actions';
function UpdateName() {
const [, submitAction] = useActionState(updateName, null, `/name/update`);
return (
<form action={submitAction}>
...
</form>
);
}
```
----------------------------------------
TITLE: Tainting Sensitive Values with `experimental_taintUniqueValue`
DESCRIPTION: This example shows how to use React's experimental `taintUniqueValue` API to proactively mark a sensitive value (like `process.env.API_PASSWORD`) as 'tainted'. If this tainted value is ever passed to a Client Component or sent to the client via a Server Function, React will throw an error with the specified message, providing an additional layer of protection against accidental secret leakage during refactoring or development.
SOURCE: https://react.dev/reference/react/experimental_taintUniqueValue
LANGUAGE: JavaScript
CODE:
```
import "server-only";
import {experimental_taintUniqueValue} from 'react';
experimental_taintUniqueValue(
'Do not pass the API token password to the client. ' +
'Instead do all fetches on the server.',
process,
process.env.API_PASSWORD
);
```
----------------------------------------
TITLE: Initial getUser Function for Database Access
DESCRIPTION: This JavaScript function demonstrates a common pattern for fetching user data from a database. It directly returns the user object, which, if not handled carefully, could lead to sensitive data being exposed to client-side components.
SOURCE: https://react.dev/reference/react/experimental_taintObjectReference
LANGUAGE: JavaScript
CODE:
```
// api.js
export async function getUser(id) {
const user = await db`SELECT * FROM users WHERE id = ${id}`;
return user;
}
```
----------------------------------------
TITLE: Incorrectly Passing Secrets from Server to Client Component
DESCRIPTION: This example demonstrates an insecure pattern where a sensitive environment variable (`process.env.API_PASSWORD`) is directly passed as a prop from a Server Component (`Dashboard`) to a Client Component (`Overview`). This action leaks the secret to the client, making it vulnerable.
SOURCE: https://react.dev/reference/react/experimental_taintUniqueValue
LANGUAGE: JavaScript
CODE:
```
export async function Dashboard(props) {
// DO NOT DO THIS
return <Overview password={process.env.API_PASSWORD} />;
}
```
----------------------------------------
TITLE: Preventing User Data Leakage in React Server Components
DESCRIPTION: Illustrates how to use `experimental_taintObjectReference` within a data fetching function (`getUser`) to prevent an entire user object, potentially containing sensitive data, from being passed to a React Client Component. It emphasizes the importance of explicitly selecting necessary properties for client-side use.
SOURCE: https://react.dev/reference/react/experimental_taintObjectReference
LANGUAGE: javascript
CODE:
```
import {experimental_taintObjectReference} from 'react';
export async function getUser(id) {
const user = await db`SELECT * FROM users WHERE id = ${id}`;
experimental_taintObjectReference(
'Do not pass the entire user object to the client. ' +
'Instead, pick off the specific properties you need for this use case.',
user,
);
return user;
}
```
----------------------------------------
TITLE: React Client Component with useActionState for Progressive Enhancement
DESCRIPTION: This example illustrates how to use `useActionState` with a third argument (a permalink) to enable progressive enhancement. If the JavaScript bundle hasn't loaded, submitting the form will redirect to the specified URL, ensuring basic functionality even before client-side hydration.
SOURCE: https://react.dev/reference/rsc/server-actions
LANGUAGE: JavaScript
CODE:
```
"use client";
import {updateName} from './actions';
function UpdateName() {
const [, submitAction] = useActionState(updateName, null, `/name/update`);
return (
<form action={submitAction}>
...
</form>
);
}
```
----------------------------------------
TITLE: React Effect for Page Visit Analytics
DESCRIPTION: This snippet demonstrates using `useEffect` to log page visits. It highlights that in development mode, the effect might run twice due to React's Strict Mode, but this behavior is normal and does not affect production. It advises against trying to 'fix' the double call in development for analytics.
SOURCE: https://react.dev/learn/synchronizing-with-effects
LANGUAGE: JavaScript
CODE:
```
useEffect(() => {
logVisit(url); // Sends a POST request
}, [url]);
```
----------------------------------------
TITLE: React Server Function: Check Username Availability
DESCRIPTION: This server-side function (`requestUsername`) processes form data to extract a username. It simulates a check for username availability and returns 'successful' or 'failed' based on a condition, demonstrating how server functions can provide direct feedback to the client.
SOURCE: https://react.dev/reference/rsc/use-server
LANGUAGE: JavaScript
CODE:
```
'use server';
export default async function requestUsername(formData) {
const username = formData = formData.get('username');
if (canRequest(username)) {
// ...
return 'successful';
}
return 'failed';
}
```
----------------------------------------
TITLE: Display Pending State and Read Form Data with useFormStatus in React
DESCRIPTION: This React component demonstrates how to use the `useFormStatus` hook to show a pending state during form submission and read the data being submitted. It disables the input and submit button while pending and displays the requested username from the form's `data` property.
SOURCE: https://react.dev/reference/react-dom/hooks/useFormStatus
LANGUAGE: javascript
CODE:
```
import {useState, useMemo, useRef} from 'react';
import {useFormStatus} from 'react-dom';
export default function UsernameForm() {
const {pending, data} = useFormStatus();
return (
<div>
<h3>Request a Username: </h3>
<input type="text" name="username" disabled={pending}/>
<button type="submit" disabled={pending}>
Submit
</button>
<br />
<p>{data ? `Requesting ${data?.get("username")}...`: ''}</p>
</div>
);
}
```
----------------------------------------
TITLE: Caching Expensive Computations with `cache` for Shared Work
DESCRIPTION: This example illustrates how `cache` can optimize performance by sharing results of expensive computations across different components. If `Profile` and `TeamReport` components both need metrics for the same `user` object, `cache` ensures that `calculateUserMetrics` is called only once for that user, and the result is shared, preventing duplicate work and improving efficiency.
SOURCE: https://react.dev/reference/react/cache
LANGUAGE: JavaScript
CODE:
```
import {cache} from 'react';
import calculateUserMetrics from 'lib/user';
const getUserMetrics = cache(calculateUserMetrics);
function Profile({user}) {
const metrics = getUserMetrics(user);
// ...
}
function TeamReport({users}) {
for (let user in users) {
const metrics = getUserMetrics(user);
// ...
}
// ...
}
```
----------------------------------------
TITLE: React DOM Server APIs Reference
DESCRIPTION: This section covers the APIs used for server-side rendering (SSR) in React DOM. These functions allow React components to be rendered to HTML strings or streams on the server.
SOURCE: https://react.dev/reference/react/cache
LANGUAGE: APIDOC
CODE:
```
Server APIs:
- renderToPipeableStream(element, options?): Renders a React tree to a Node.js Writable stream, allowing for streaming HTML responses.
- renderToReadableStream(element, options?): Renders a React tree to a Web ReadableStream, suitable for environments like Cloudflare Workers or Deno.
- renderToStaticMarkup(element): Renders a React element to its initial HTML. React will not add any React-specific attributes or extra DOM, and will not hydrate it on the client.
- renderToString(element): Renders a React element to its initial HTML. React will attach event handlers to this markup on the client.
```
----------------------------------------
TITLE: Correct React.cache Usage: Passing Primitive Arguments
DESCRIPTION: This example demonstrates the correct way to use `React.cache` by passing primitive values as arguments. When primitives are passed, React's shallow equality check succeeds if the values are identical, ensuring that the memoized function only re-executes when its inputs truly change.
SOURCE: https://react.dev/reference/react/cache
LANGUAGE: javascript
CODE:
```
import {cache} from 'react';
const calculateNorm = cache((x, y, z) => {
// ...
});
function MapMarker(props) {
// ✅ Good: Pass primitives to memoized function
const length = calculateNorm(props.x, props.y, props.z);
// ...
}
function App() {
return (
<>
<MapMarker x={10} y={10} z={10} />
<MapMarker x={10} y={10} z={10} />
</>
);
}
```
----------------------------------------
TITLE: React DOM useFormStatus Hook for Form Status Access
DESCRIPTION: The `useFormStatus` hook provides a convenient way for child components within a form to access the status of their parent `<form>`, such as its `pending` state. This eliminates the need for prop drilling, making it easier to build design components that react to form submission status.
SOURCE: https://react.dev/blog/2024/04/25/react-19
LANGUAGE: javascript
CODE:
```
import {useFormStatus} from 'react-dom';
function DesignButton() {
const {pending} = useFormStatus();
return <button type="submit" disabled={pending} />
}
```
----------------------------------------
TITLE: Demonstrate Multiple Instances of a Component with `useId`
DESCRIPTION: This `App.js` example shows how a React component (`PasswordField`) that uses `useId` can be rendered multiple times within an application. The `useId` hook ensures that each instance of `PasswordField` generates unique IDs, preventing conflicts and maintaining accessibility.
SOURCE: https://react.dev/reference/react/useId
LANGUAGE: javascript
CODE:
```
import { useId } from 'react';
function PasswordField() {
const passwordHintId = useId();
return (
<>
<label>
Password:
<input
type="password"
aria-describedby={passwordHintId}
/>
</label>
<p id={passwordHintId}>
The password should contain at least 18 characters
</p>
</>
);
}
export default function App() {
return (
<>
<h2>Choose password</h2>
<PasswordField />
<h2>Confirm password</h2>
<PasswordField />
</>
);
}
```
----------------------------------------
TITLE: Memoizing Expensive Computations with React `useMemo`
DESCRIPTION: This snippet shows how `useMemo` is used in Client Components to cache the result of an expensive computation across renders. It ensures that if the dependencies (e.g., `record`) do not change, the computation is skipped, and the previously memoized value is returned. The cache is local to the component instance.
SOURCE: https://react.dev/reference/react/cache
LANGUAGE: JavaScript
CODE:
```
'use client';
function WeatherReport({record}) {
const avgTemp = useMemo(() => calculateAvg(record), record);
// ...
}
function App() {
const record = getRecord();
return (
<>
<WeatherReport record={record} />
<WeatherReport record={record} />
</>
);
}
```
----------------------------------------
TITLE: Server Function Form Submission with Hidden Fields
DESCRIPTION: This snippet demonstrates how to use a Server Function (marked with `'use server'`) as the `action` for a React form. It shows how to pass additional data, such as a `productId`, to the server function using a hidden input field within the form, enabling progressive enhancement.
SOURCE: https://react.dev/reference/react-dom/components/form
LANGUAGE: JavaScript
CODE:
```
import { updateCart } from './lib.js';
function AddToCart({productId}) {
async function addToCart(formData) {
'use server'
const productId = formData.get('productId')
await updateCart(productId)
}
return (
<form action={addToCart}>
<input type="hidden" name="productId" value={productId} />
<button type="submit">Add to Cart</button>
</form>
);
}
```
----------------------------------------
TITLE: React Server Component Passing Full User Object to Client Component
DESCRIPTION: This React Server Component illustrates a potential security vulnerability. It fetches a complete user object and then passes the entire object directly as a prop to a client-side `InfoCard` component, which is explicitly marked as an insecure practice.
SOURCE: https://react.dev/reference/react/experimental_taintObjectReference
LANGUAGE: JavaScript
CODE:
```
import { getUser } from 'api.js';
import { InfoCard } from 'components.js';
export async function Profile(props) {
const user = await getUser(props.userId);
// DO NOT DO THIS
return <InfoCard user={user} />;
}
```
----------------------------------------
TITLE: Complete React Component Using `useId` for Unique IDs
DESCRIPTION: Provides a complete React functional component (`PasswordField`) that utilizes the `useId` hook to generate a unique ID for accessibility attributes. This ensures IDs do not clash when the component is rendered multiple times on the same page, making it suitable for reusable components.
SOURCE: https://react.dev/reference/react/useId
LANGUAGE: javascript
CODE:
```
import { useId } from 'react';
function PasswordField() {
const passwordHintId = useId();
return (
<>
<label>
Password:
<input
type="password"
aria-describedby={passwordHintId}
/>
</label>
<p id={passwordHintId}>
The password should contain at least 18 characters
</p>
</>
);
}
```
----------------------------------------
TITLE: Tainting a Value Tied to an Object's Lifetime
DESCRIPTION: Shows how to taint a value, like a user session token, where the taint's lifetime is bound to a specific object (e.g., a `user` object). This ensures the value remains protected as long as the encapsulating object exists.
SOURCE: https://react.dev/reference/react/experimental_taintUniqueValue
LANGUAGE: JavaScript
CODE:
```
import {experimental_taintUniqueValue} from 'react';
export async function getUser(id) {
const user = await db`SELECT * FROM users WHERE id = ${id}`;
experimental_taintUniqueValue(
'Do not pass a user session token to the client.',
user,
user.session.token
);
return user;
}
```
----------------------------------------
TITLE: React Server Function: Increment Like Count
DESCRIPTION: This simple server-side function (`incrementLike`) demonstrates a basic operation that can be performed on the server. It increments a global `likeCount` variable and returns its updated value, showcasing how server functions can maintain and update state across client requests.
SOURCE: https://react.dev/reference/rsc/use-server
LANGUAGE: JavaScript
CODE:
```
'use server';
let likeCount = 0;
export default async function incrementLike() {
likeCount++;
return likeCount;
}
```
----------------------------------------
TITLE: Legacy React APIs Reference
DESCRIPTION: This section provides a reference to older or less commonly used APIs from the main 'react' package. While still available, newer patterns (like Hooks) are often preferred.
SOURCE: https://react.dev/reference/react/cache
LANGUAGE: APIDOC
CODE:
```
Legacy React APIs:
- Children: Utilities for working with the `props.children` opaque data structure.
- cloneElement(element, props, ...children): Clones and returns a new React element using `element` as the starting point.
- Component: The base class for defining React class components.
- createElement(type, props, ...children): Creates and returns a new React element of the given type.
- createRef(): Creates a ref that can be attached to a React element.
- forwardRef(render): Creates a React component that forwards the ref attribute to a child component.
- isValidElement(object): Verifies whether an object is a React element.
- PureComponent: A base class for defining React class components that implements a shallow comparison for `shouldComponentUpdate`.
```
----------------------------------------
TITLE: Correct useFormStatus Usage: Component Inside Form
DESCRIPTION: Demonstrates the correct pattern for using `useFormStatus`, where the component calling the hook (`Submit`) is rendered as a child *inside* the `<form>`. This allows `useFormStatus` to correctly derive and return the `pending` status from its parent form.
SOURCE: https://react.dev/reference/react-dom/hooks/useFormStatus
LANGUAGE: javascript
CODE:
```
function Submit() {
// ✅ `pending` will be derived from the form that wraps the Submit component
const { pending } = useFormStatus();
return <button disabled={pending}>...</button>;
}
function Form() {
// This is the <form> `useFormStatus` tracks
return (
<form action={submit}>
<Submit />
</form>
);
}
```
----------------------------------------
TITLE: Server Functions with Manual Actions and useTransition
DESCRIPTION: This example demonstrates how to integrate a server function with React's action pattern, specifically using `useTransition` to manage pending states. A server function is defined to update user data, and a client component wraps its invocation within `startTransition` to track loading states and handle potential errors.
SOURCE: https://react.dev/reference/rsc/server-actions
LANGUAGE: JavaScript
CODE:
```
"use server";
export async function updateName(name) {
if (!name) {
return {error: 'Name is required'};
}
await db.users.updateName(name);
}
```
LANGUAGE: JavaScript
CODE:
```
"use client";
import {updateName} from './actions';
import {useState, useTransition} from 'react';
function UpdateName() {
const [name, setName] = useState('');
const [error, setError] = useState(null);
const [isPending, startTransition] = useTransition();
const submitAction = async () => {
startTransition(async () => {
const {error} = await updateName(name);
if (error) {
setError(error);
} else {
setName('');
}
})
}
return (
<form action={submitAction}>
<input type="text" name="name" disabled={isPending}/>
{error && <span>Failed: {error}</span>}
</form>
)
}
```
----------------------------------------
TITLE: Cache Function for React Server Components
DESCRIPTION: The `cache` function is designed for use with React Server Components to memoize the result of a data fetch or computation. It helps optimize performance by preventing redundant executions of expensive operations.
SOURCE: https://react.dev/reference/react/cache
LANGUAGE: APIDOC
CODE:
```
cache(fn):
- Purpose: Caches the result of a function call.
- Parameters:
- fn: The function whose result is to be cached. This function should be pure and deterministic.
- Returns: A memoized version of the input function `fn`.
- Usage:
- Cache an expensive computation: Prevents re-running CPU-intensive calculations.
- Share a snapshot of data: Ensures all callers get the same data instance within a request.
- Preload data: Can be used to fetch data once and reuse it across multiple components.
- Note: `cache` is only for use with React Server Components.
```
----------------------------------------
TITLE: Basic Usage of React `cache` for Function Memoization
DESCRIPTION: This snippet demonstrates the fundamental usage of the `cache` function from React. It shows how to wrap an expensive computation function (`calculateMetrics`) with `cache` to create a memoized version (`getMetrics`). When `getMetrics` is called with specific data, it computes and caches the result, returning the cached value for subsequent calls with the same data, thus avoiding redundant computations.
SOURCE: https://react.dev/reference/react/cache
LANGUAGE: JavaScript
CODE:
```
import {cache} from 'react';
import calculateMetrics from 'lib/metrics';
const getMetrics = cache(calculateMetrics);
function Chart({data}) {
const report = getMetrics(data);
// ...
}
```
----------------------------------------
TITLE: React `useEffect` with `experimental_useEffectEvent` for Controlled Re-runs
DESCRIPTION: This snippet demonstrates how to use the experimental `useEffectEvent` hook to prevent unwanted re-runs of a `useEffect`. By moving the `showNotification` logic into an `useEffectEvent`, the `theme` dependency is removed from the main `useEffect`, ensuring the chat connection only re-establishes when `roomId` changes.
SOURCE: https://react.dev/learn/escape-hatches
LANGUAGE: javascript
CODE:
```
import { useState, useEffect } from 'react';
import { experimental_useEffectEvent as useEffectEvent } from 'react';
import { createConnection, sendMessage } from './chat.js';
import { showNotification } from './notifications.js';
const serverUrl = 'https://localhost:1234';
function ChatRoom({ roomId, theme }) {
const onConnected = useEffectEvent(() => {
showNotification('Connected!', theme);
});
useEffect(() => {
const connection = createConnection(serverUrl, roomId);
connection.on('connected', () => {
onConnected();
});
connection.connect();
return () => connection.disconnect();
}, [roomId]);
return <h1>Welcome to the {roomId} room!</h1>
}
export default function App() {
const [roomId, setRoomId] = useState('general');
const [isDark, setIsDark] = useState(false);
return (
<>
<label>
Choose the chat room:{' '}
<select
value={roomId}
onChange={e => setRoomId(e.target.value)}
>
<option value="general">general</option>
<option value="travel">travel</option>
<option value="music">music</option>
</select>
</label>
<label>
<input
type="checkbox"
checked={isDark}
onChange={e => setIsDark(e.target.checked)}
/>
Use dark theme
</label>
<hr />
<ChatRoom
roomId={roomId}
theme={isDark ? 'dark' : 'light'}
/>
</>
);
}
```
----------------------------------------
TITLE: React Client Component: Calling Server Function with useTransition
DESCRIPTION: This React client component (`LikeButton`) illustrates how to call a server function (`incrementLike`) outside of a standard HTML form. It uses `useTransition` to manage the pending state during the asynchronous server function call, allowing for UI updates like disabling a button and displaying a loading indicator.
SOURCE: https://react.dev/reference/rsc/use-server
LANGUAGE: JavaScript
CODE:
```
import incrementLike from './actions';
import { useState, useTransition } from 'react';
function LikeButton() {
const [isPending, startTransition] = useTransition();
const [likeCount, setLikeCount] = useState(0);
const onClick = () => {
startTransition(async () => {
const currentCount = await incrementLike();
setLikeCount(currentCount);
});
};
return (
<>
<p>Total Likes: {likeCount}</p>
<button onClick={onClick} disabled={isPending}>Like</button>;
</>
);
}
```
----------------------------------------
TITLE: Wait for All Content to Load in React Server-Side Rendering for SEO/Crawlers
DESCRIPTION: This JavaScript example shows how to ensure that all content is fully loaded before sending the HTML response, which is beneficial for web crawlers or static site generation. It leverages the `stream.allReady` Promise to await the completion of all rendering, allowing the server to send a complete HTML document rather than a progressive stream.
SOURCE: https://react.dev/reference/react-dom/server/renderToReadableStream
LANGUAGE: JavaScript
CODE:
```
async function handler(request) {
try {
let didError = false;
const stream = await renderToReadableStream(<App />, {
bootstrapScripts: ['/main.js'],
onError(error) {
didError = true;
console.error(error);
logServerCrashReport(error);
}
});
let isCrawler = // ... depends on your bot detection strategy ...
if (isCrawler) {
await stream.allReady;
}
return new Response(stream, {
status: didError ? 500 : 200,
headers: { 'content-type': 'text/html' },
});
} catch (error) {
return new Response('<h1>Something went wrong</h1>', {
status: 500,
headers: { 'content-type': 'text/html' },
});
}
}
```
----------------------------------------
TITLE: Incorrect useFormStatus Usage: Same Component Form Tracking
DESCRIPTION: Illustrates a common pitfall where `useFormStatus` is called within the same component that renders the `<form>` it intends to track. This is incorrect because `useFormStatus` only tracks status information for a *parent* `<form>`, meaning `pending` will never be true in this scenario.
SOURCE: https://react.dev/reference/react-dom/hooks/useFormStatus
LANGUAGE: javascript
CODE:
```
function Form() {
// 🚩 `pending` will never be true
// useFormStatus does not track the form rendered in this component
const { pending } = useFormStatus();
return <form action={submit}></form>;
}
```
----------------------------------------
TITLE: Memoizing Expensive Calculations with React useMemo Hook
DESCRIPTION: This code demonstrates how to use the `useMemo` hook to cache the result of an expensive calculation, `getFilteredTodos`. The calculation will only re-run if `todos` or `filter` (dependencies) change, preventing unnecessary re-computation on unrelated state updates and improving performance.
SOURCE: https://react.dev/learn/you-might-not-need-an-effect
LANGUAGE: javascript
CODE:
```
import { useMemo, useState } from 'react';
function TodoList({ todos, filter }) {
const [newTodo, setNewTodo] = useState('');
const visibleTodos = useMemo(() => {
// ✅ Does not re-run unless todos or filter change
return getFilteredTodos(todos, filter);
}, [todos, filter]);
// ...
}
```
----------------------------------------
TITLE: React DOM Client APIs Reference
DESCRIPTION: This section details the APIs specifically designed for client-side rendering and hydration in React DOM. These functions are used to mount and update React applications in a browser environment.
SOURCE: https://react.dev/reference/react/cache
LANGUAGE: APIDOC
CODE:
```
Client APIs:
- createRoot(domNode, options?): Creates a React root for displaying content in a browser DOM node. This is the entry point for client-side rendering with React 18+.
- hydrateRoot(domNode, reactNode, options?): Hydrates a React root that was previously rendered on the server, attaching event listeners and making it interactive.
```
----------------------------------------
TITLE: React `experimental_taintUniqueValue` API Reference
DESCRIPTION: The `experimental_taintUniqueValue` function is a React API used to mark a specific value as 'tainted'. If this tainted value is ever passed to a Client Component or sent to the client via a Server Function, React will throw an error, preventing accidental data leakage. This is particularly useful for protecting sensitive server-side data.
SOURCE: https://react.dev/reference/react/experimental_taintUniqueValue
LANGUAGE: APIDOC
CODE:
```
taintUniqueValue(message: string, lifetime: any, value: any)
Parameters:
- message: string
A descriptive error message that will be thrown if the tainted value is passed to the client.
- lifetime: any
An object that defines the 'lifetime' or scope of the tainted value. If this object is garbage collected, the taint is removed. Typically, `process` or a specific module object is used.
- value: any
The specific value to be tainted (e.g., a secret API key, a password).
Returns:
- void
Usage Notes:
- This API is experimental and subject to change.
- It should be used on the server-side to protect values that must never reach the client.
- The error is thrown at runtime when the tainted value is detected crossing the server-client boundary.
```
----------------------------------------
TITLE: React Profile Page with Suspense for Posts
DESCRIPTION: This example demonstrates how to wrap a potentially slow-loading component (`Posts`) with a `<Suspense>` boundary. React will stream the HTML for the `PostsGlimmer` fallback initially, then replace it with the actual `Posts` content once its data is loaded, improving perceived performance.
SOURCE: https://react.dev/reference/react-dom/server/renderToReadableStream
LANGUAGE: javascript
CODE:
```
function ProfilePage() {
return (
<ProfileLayout>
<ProfileCover />
<Sidebar>
<Friends />
<Photos />
</Sidebar>
<Suspense fallback={<PostsGlimmer />}>
<Posts />
</Suspense>
</ProfileLayout>
);
}
```
----------------------------------------
TITLE: React Client Component Displaying User Information
DESCRIPTION: This is a simple React Client Component designed to display user information. It expects a `user` object as a prop and accesses its `name` property. In a secure application, this component should only receive the necessary, non-sensitive data.
SOURCE: https://react.dev/reference/react/experimental_taintObjectReference
LANGUAGE: JavaScript
CODE:
```
// components.js
"use client";
export async function InfoCard({ user }) {
return <div>{user.name}</div>;
}
```
----------------------------------------
TITLE: Type-Safe Lazy Ref Initialization with Getter Function
DESCRIPTION: For scenarios requiring type safety and avoiding null checks, this pattern wraps the lazy initialization logic within a getter function. The `playerRef` itself remains nullable, but the `getPlayer()` function ensures a non-null instance is always returned, making it easier to work with type checkers.
SOURCE: https://react.dev/reference/react/useRef
LANGUAGE: JavaScript
CODE:
```
function Video() {
const playerRef = useRef(null);
function getPlayer() {
if (playerRef.current !== null) {
return playerRef.current;
}
const player = new VideoPlayer();
playerRef.current = player;
return player;
}
// ...
}
```
----------------------------------------
TITLE: React DOM Static APIs Reference
DESCRIPTION: This section lists APIs related to static rendering or pre-rendering, often used for generating static HTML files or for specific server-side rendering scenarios.
SOURCE: https://react.dev/reference/react/cache
LANGUAGE: APIDOC
CODE:
```
Static APIs:
- prerender(element, options?): Pre-renders a React tree to static HTML, typically used for static site generation.
- prerenderToNodeStream(element, options?): Pre-renders a React tree to a Node.js stream for static output.
```
----------------------------------------
TITLE: Sharing Memoized Data Fetches Across Server Components with React `cache`
DESCRIPTION: This example demonstrates using React's `cache` in Server Components to memoize data fetches, allowing multiple components to share the same cached data. Unlike `useMemo`, `cache` is suitable for data fetching and enables different component instances to access a shared cache, preventing duplicate work for identical requests.
SOURCE: https://react.dev/reference/react/cache
LANGUAGE: JavaScript
CODE:
```
const cachedFetchReport = cache(fetchReport);
function WeatherReport({city}) {
const report = cachedFetchReport(city);
// ...
}
function App() {
const city = "Los Angeles";
return (
<>
<WeatherReport city={city} />
<WeatherReport city={city} />
</>
);
}
```
----------------------------------------
TITLE: Specify Global ID Prefix for Multiple React Apps on a Page
DESCRIPTION: Illustrates how to use `identifierPrefix` with `createRoot` or `hydrateRoot` when rendering multiple independent React applications on the same page. This prevents ID clashes by ensuring all IDs generated by `useId` within an app start with a distinct, specified prefix.
SOURCE: https://react.dev/reference/react/useId
LANGUAGE: JavaScript
CODE:
```
import { createRoot } from 'react-dom/client';
import App from './App.js';
import './styles.css';
const root1 = createRoot(document.getElementById('root1'), {
identifierPrefix: 'my-first-app-'
});
root1.render(<App />);
const root2 = createRoot(document.getElementById('root2'), {
identifierPrefix: 'my-second-app-'
});
root2.render(<App />);
```
----------------------------------------
TITLE: Adding Server Rendering Support to a React Hook
DESCRIPTION: This snippet extends the `useOnlineStatus` hook to support server-side rendering by including a `getServerSnapshot` function as the third argument to `useSyncExternalStore`. The `getServerSnapshot` provides an initial snapshot value for server-generated HTML and client hydration, ensuring consistent behavior across environments.
SOURCE: https://react.dev/reference/react/useSyncExternalStore
LANGUAGE: javascript
CODE:
```
import { useSyncExternalStore } from 'react';
export function useOnlineStatus() {
const isOnline = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
return isOnline;
}
function getSnapshot() {
return navigator.onLine;
}
function getServerSnapshot() {
return true; // Always show "Online" for server-generated HTML
}
function subscribe(callback) {
// ...
}
```
----------------------------------------
TITLE: React App State Preservation with Activity
DESCRIPTION: This snippet shows how to modify the previous `App` component to use `<Activity>` for state preservation. By wrapping the `<Home />` component with `<Activity>` and toggling its `mode` based on the URL, the state of `<Home />` is retained even when the user navigates away and then returns.
SOURCE: https://react.dev/blog/2025/04/23/react-labs-view-transitions-activity-and-more
LANGUAGE: JavaScript
CODE:
```
function App() {
const { url } = useRouter();
return (
<>
<Activity mode={url === '/' ? 'visible' : 'hidden'}>
<Home />
</Activity>
{url !== '/' && <Details />}
</>
);
}
```
----------------------------------------
TITLE: Integrating React Server Function with HTML Form Action
DESCRIPTION: This JavaScript snippet demonstrates how to use a React Server Function directly as the 'action' handler for an HTML form. When the form is submitted, React automatically invokes the server function, passing the form's FormData object as its first argument. This pattern enables server-side data mutations with progressive enhancement, allowing the form to function even before the client-side JavaScript bundle loads.
SOURCE: https://react.dev/reference/rsc/use-server
LANGUAGE: JavaScript
CODE:
```
// App.js
async function requestUsername(formData) {
'use server';
const username = formData.get('username');
// ...
}
export default function App() {
return (
<form action={requestUsername}>
<input type="text" name="username" />
<button type="submit">Request</button>
</form>
);
}
```
----------------------------------------
TITLE: React DOM HTML Elements Reference
DESCRIPTION: This section provides a reference to common HTML elements that React DOM supports as components. These are standard HTML tags that can be used directly within JSX.
SOURCE: https://react.dev/reference/react/cache
LANGUAGE: APIDOC
CODE:
```
Components:
- Common (e.g. <div>): Standard HTML elements like div, span, p, etc.
- <form>: HTML form element.
- <input>: HTML input element.
- <option>: HTML option element for select.
- <progress>: HTML progress element.
- <select>: HTML select element.
- <textarea>: HTML textarea element.
- <link>: HTML link element.
- <meta>: HTML meta element.
- <script>: HTML script element.
- <style>: HTML style element.
- <title>: HTML title element.
```
----------------------------------------
TITLE: Incorrect React.cache Usage with Object Props (Shallow Equality Pitfall)
DESCRIPTION: This snippet illustrates a common pitfall when using `React.cache` (or similar memoization techniques) with non-primitive arguments. Passing a new object reference (like the `props` object) on every render, even if its internal values are the same, causes the memoized function to re-run because React's shallow equality check (`Object.is`) fails.
SOURCE: https://react.dev/reference/react/cache
LANGUAGE: javascript
CODE:
```
import {cache} from 'react';
const calculateNorm = cache((vector) => {
// ...
});
function MapMarker(props) {
// 🚩 Wrong: props is an object that changes every render.
const length = calculateNorm(props);
// ...
}
function App() {
return (
<>
<MapMarker x={10} y={10} z={10} />
<MapMarker x={10} y={10} z={10} />
</>
);
}
```
----------------------------------------
TITLE: Implementing a useOnlineStatus Custom Hook with useDebugValue and useSyncExternalStore
DESCRIPTION: A complete implementation of a `useOnlineStatus` custom hook that leverages `useSyncExternalStore` to subscribe to browser online/offline events and `useDebugValue` to provide a clear debug label in React DevTools. This hook returns the current online status.
SOURCE: https://react.dev/reference/react/useDebugValue
LANGUAGE: JavaScript
CODE:
```
import { useSyncExternalStore, useDebugValue } from 'react';
export function useOnlineStatus() {
const isOnline = useSyncExternalStore(subscribe, () => navigator.onLine, () => true);
useDebugValue(isOnline ? 'Online' : 'Offline');
return isOnline;
}
function subscribe(callback) {
window.addEventListener('online', callback);
window.addEventListener('offline', callback);
return () => {
window.removeEventListener('online', callback);
window.removeEventListener('offline', callback);
};
}
```
----------------------------------------
TITLE: React DOM Hooks Reference
DESCRIPTION: This section lists the hooks available in React DOM, providing a quick reference to their names. Hooks are functions that let you 'hook into' React state and lifecycle features from function components.
SOURCE: https://react.dev/reference/react/cache
LANGUAGE: APIDOC
CODE:
```
Hooks:
- useFormStatus: Allows components to read the pending state of a form submission.
```
----------------------------------------
TITLE: Consuming a shared memoized function in React components
DESCRIPTION: These examples show how React components (`Temperature` and `Precipitation`) correctly import and utilize a shared memoized function. By calling the same memoized function from a central module, both components access the same cache, maximizing cache hits and reducing duplicate work when processing identical inputs.
SOURCE: https://react.dev/reference/react/cache
LANGUAGE: javascript
CODE:
```
// Temperature.js
import getWeekReport from './getWeekReport';
export default function Temperature({cityData}) {
const report = getWeekReport(cityData);
// ...
}
```
LANGUAGE: javascript
CODE:
```
// Precipitation.js
import getWeekReport from './getWeekReport';
export default function Precipitation({cityData}) {
const report = getWeekReport(cityData);
// ...
}
```
----------------------------------------
TITLE: React Server Components: 'use server' Directive
DESCRIPTION: The `'use server'` directive is used in React to mark functions or modules that are intended to run exclusively on the server. This enables server-side logic, such as database mutations or secure API calls, to be directly invoked from client components as Server Actions.
SOURCE: https://react.dev/blog/2024/02/15/react-labs-what-we-have-been-working-on-february-2024
LANGUAGE: APIDOC
CODE:
```
'use server'
- Purpose: Designates a function or an entire module to be executed on the server.
- Usage: Placed at the top of a file to mark all exports as server functions, or at the top of a specific function body to mark only that function.
- Context: Essential for creating Server Actions that can be passed to client components (e.g., as a form's `action` prop) and executed securely on the server.
```
----------------------------------------
TITLE: Correct React.cache Usage: Passing Same Object Reference
DESCRIPTION: This snippet shows another correct approach for using `React.cache` with objects. By ensuring that the same object reference is passed to the memoized function across renders (e.g., by defining it outside the component or memoizing it), React's shallow equality check will pass, allowing the memoized result to be reused.
SOURCE: https://react.dev/reference/react/cache
LANGUAGE: javascript
CODE:
```
import {cache} from 'react';
const calculateNorm = cache((vector) => {
// ...
});
function MapMarker(props) {
// ✅ Good: Pass the same `vector` object
const length = calculateNorm(props.vector);
// ...
}
function App() {
const vector = [10, 10, 10];
return (
<>
<MapMarker vector={vector} />
<MapMarker vector={vector} />
</>
);
}
```
----------------------------------------
TITLE: Reading External Store with React 19 use API
DESCRIPTION: This snippet demonstrates the new `use` API introduced in React 19 for reading values from external stores. It is designed to integrate seamlessly with React's concurrent features, aiming to prevent tearing and avoid forcing bailouts from concurrent rendering, which was a limitation of `useSyncExternalStore`.
SOURCE: https://react.dev/blog/2025/04/23/react-labs-view-transitions-activity-and-more
LANGUAGE: JavaScript
CODE:
```
const value = use(store);
```
----------------------------------------
TITLE: React Server Components Directives
DESCRIPTION: This section describes special directives used within React Server Components to define module boundaries and client/server code separation. These directives are crucial for building applications with React Server Components.
SOURCE: https://react.dev/reference/react/cache
LANGUAGE: APIDOC
CODE:
```
Directives:
- 'use client': Marks a module and its exports as client-side code, which will be bundled and executed on the client.
- 'use server': Marks a module or function as server-side code, allowing it to be called from client components.
```
----------------------------------------
TITLE: React Activity Component and Related APIs
DESCRIPTION: This section details the behavior and best practices for using the React `Activity` component, especially concerning its `mode` prop and interaction with Server-Side Rendering (SSR). It also explains how `StrictMode` can help identify problematic side-effects and suggests `useDeferredValue` as an alternative for including hidden content in SSR.
SOURCE: https://react.dev/reference/react/Activity
LANGUAGE: APIDOC
CODE:
```
Activity Component:
- Concept: Behaves like 'unmounting' and 'remounting' a component, but saves React or DOM state.
- Usage:
- <Activity mode="visible" | "hidden">: Controls the visibility and lifecycle of its children.
- mode="hidden": Content is not rendered during Server-Side Rendering (SSR).
- Troubleshooting:
- Effects don’t mount when an Activity is hidden: This is expected behavior as the component is conceptually 'unmounted'.
- My hidden Activity is not rendered in SSR: Content within <Activity mode="hidden"> is excluded from SSR responses. Use `useDeferredValue` for deferred rendering if SSR inclusion is needed.
StrictMode Component:
- <StrictMode>: A development tool that helps identify unexpected side-effects.
- Purpose: Eagerly performs Activity unmounts and mounts to catch problematic Effects.
useDeferredValue Hook:
- Purpose: Defers rendering of a value, allowing non-urgent updates to be rendered later.
- Usage: Can be used as an alternative to <Activity mode="hidden"> if content needs to be included in the SSR response but rendered later on the client.
```
----------------------------------------
TITLE: Wait for All Content to Load for Crawlers using React renderToPipeableStream
DESCRIPTION: This snippet demonstrates how to use the `onAllReady` callback with `renderToPipeableStream` to ensure all content is fully loaded before sending the HTML response. This is particularly useful for crawlers or static site generation, allowing them to receive a complete page rather than a progressively streamed one, while regular users still benefit from streaming.
SOURCE: https://react.dev/reference/react-dom/server/renderToPipeableStream
LANGUAGE: javascript
CODE:
```
let didError = false;
let isCrawler = // ... depends on your bot detection strategy ...
const { pipe } = renderToPipeableStream(<App />, {
bootstrapScripts: ['/main.js'],
onShellReady() {
if (!isCrawler) {
response.statusCode = didError ? 500 : 200;
response.setHeader('content-type', 'text/html');
pipe(response);
}
},
onShellError(error) {
response.statusCode = 500;
response.setHeader('content-type', 'text/html');
response.send('<h1>Something went wrong</h1>');
},
onAllReady() {
if (isCrawler) {
response.statusCode = didError ? 500 : 200;
response.setHeader('content-type', 'text/html');
pipe(response);
}
},
onError(error) {
didError = true;
console.error(error);
logServerCrashReport(error);
}
});
```
----------------------------------------
TITLE: Global Application Initialization Logic
DESCRIPTION: This example shows how to execute logic only once when the application starts, outside of React components. It includes a check for the `window` object to ensure the code runs specifically in a browser environment, suitable for tasks like checking authentication tokens or loading data from local storage.
SOURCE: https://react.dev/learn/synchronizing-with-effects
LANGUAGE: JavaScript
CODE:
```
if (typeof window !== 'undefined') { // Check if we're running in the browser.
checkAuthToken();
loadDataFromLocalStorage();
}
function App() {
// ...
}
```
----------------------------------------
TITLE: Basic React useFormStatus Hook Usage
DESCRIPTION: Demonstrates how to import and use the `useFormStatus` hook within a React component to get the submission status of a parent form, disabling a button during the pending state. The `Submit` component must be rendered inside a `<form>` for the hook to function correctly.
SOURCE: https://react.dev/reference/react-dom/hooks/useFormStatus
LANGUAGE: javascript
CODE:
```
import { useFormStatus } from "react-dom";
import action from './actions';
function Submit() {
const status = useFormStatus();
return <button disabled={status.pending}>Submit</button>
}
export default function App() {
return (
<form action={action}>
<Submit />
</form>
);
}
```