========================
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 (
);
}
```
----------------------------------------
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 (
);
}
```
----------------------------------------
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 ;
}
```
----------------------------------------
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 (
);
}
```
----------------------------------------
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 (
);
}
```
----------------------------------------
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 (
<>
>
);
}
```
----------------------------------------
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 `
);
}
```
----------------------------------------
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 ;
}
```
----------------------------------------
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 (
<>
The password should contain at least 18 characters
>
);
}
```
----------------------------------------
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 `
);
}
```
----------------------------------------
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 (
)
}
```
----------------------------------------
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
Welcome to the {roomId} room!
}
export default function App() {
const [roomId, setRoomId] = useState('general');
const [isDark, setIsDark] = useState(false);
return (
<>
>
);
}
```
----------------------------------------
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 (
<>
Total Likes: {likeCount}
;
>
);
}
```
----------------------------------------
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(, {
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('
Something went wrong
', {
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 `;
}
```
----------------------------------------
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 `` 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 (
}>
);
}
```
----------------------------------------
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
{user.name}
;
}
```
----------------------------------------
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 (
<>
>
);
}
```
----------------------------------------
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();
const root2 = createRoot(document.getElementById('root2'), {
identifierPrefix: 'my-second-app-'
});
root2.render();
```
----------------------------------------
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 `` for state preservation. By wrapping the `` component with `` and toggling its `mode` based on the URL, the state of `` 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 (
<>
{url !== '/' && }
>
);
}
```
----------------------------------------
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 (
);
}
```
----------------------------------------
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.
): Standard HTML elements like div, span, p, etc.
-