new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

React · API reference · all subjects

react

460 notes in this subject, read out of this brain and free to use. This is page 3 of 8.

cacheSignal function signature

cacheSignal is a function that takes no parameters and returns either an AbortSignal or null. It is called without arguments: cacheSignal().

cacheSignal returns AbortSignal or null

cacheSignal() returns an AbortSignal if called during rendering. Otherwise it returns null. The AbortSignal is aborted when React has finished rendering, whether rendering completed successfully, was aborted, or failed.

cacheSignal is for React Server Components only

cacheSignal is currently for use in React Server Components only. In Client Components, it will always return null. In the future it will also be used for Client Components when a client cache refreshes or invalidates.

cacheSignal rendering completion criteria

The AbortSignal returned by cacheSignal is aborted when rendering is considered finished, which occurs when: React has successfully completed rendering, the render was aborted, or the render has failed.

Example: Ignore cancellation errors after rendering

import {cacheSignal} from "react"; import {queryDatabase, logError} from "./database"; async function getData(id) { try { return await queryDatabase(id); } catch (x) { if (!cacheSignal()?.aborted) { // only log if it's a real error and not due to cancellation logError(x); } return null; } } async function Component({id}) { const data = await getData(id); if (data === null) { return <div>No data available</div>; } return <div>{data.name}</div>; }

Example: Cancel in-flight requests with cacheSignal

import {cache, cacheSignal} from 'react'; const dedupedFetch = cache(fetch); async function Component() { await dedupedFetch(url, { signal: cacheSignal() }); }

Check cacheSignal aborted property for cancellation

The aborted property of the AbortSignal returned by cacheSignal can be checked to determine if an error was due to cancellation: cacheSignal()?.aborted. This is useful for distinguishing real errors from cancellation errors.

cacheSignal cannot abort work started outside rendering

cacheSignal cannot be used to abort async work that was started outside of rendering. If a fetch request is initiated outside of a component render but awaited inside it, the request will not be aborted when rendering finishes.

cacheSignal returns null outside of rendering

If cacheSignal is called outside of rendering, it will return null to make it clear that the current scope is not cached forever.

cache() caveats and limitations

React invalidates the cache for all memoized functions for each server request. Each call to cache() creates a new function, so calling cache() with the same function multiple times returns different memoized functions that do not share the same cache. The cached function also caches errors: if the original function throws an error for certain arguments, the error is cached and re-thrown when the cached function is called with those same arguments. cache() is for Server Components only.

cache() does not call function during creation

cache() returns a cached version of the function without calling the function in the process. The function is only called when there is a cache miss.

cache() behavior and memoization

When a cached function is called with given arguments, it first checks if a cached result exists. If a cached result exists, it returns the result immediately. If not, it calls the original function with the arguments, stores the result in the cache, and returns the result. The process is known as memoization.

cache() with asynchronous functions

When an asynchronous function is evaluated, it returns a Promise. When cache() wraps an async function, it caches the Promise itself. Subsequent calls with the same arguments return the same Promise. This allows one component to call the cached function without awaiting to start the async work, while another component can await the same Promise to get the result when it completes.

Comparison: cache vs memo

memo() prevents a component from re-rendering if its props are unchanged. It memoizes based on whether props changed, not specific computations. memo() caches only the last render with the last prop values, and invalidates when props change. cache() memoizes function results across components sharing the same cached function.

Example: Fix cache miss with non-primitive arguments

```js import {cache} from 'react'; const calculateNorm = cache((x, y, z) => { // ... }); function MapMarker(props) { // 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} /> </> ); } ``` To ensure cache hits with numeric arguments, pass individual primitives rather than object references. Alternatively, pass the same object reference to both component instances.

Example: Preload data with cache

```js const getUser = cache(async (id) => { return await db.user.query(id); }); async function Profile({id}) { const user = await getUser(id); return ( <section> <img src={user.profilePic} /> <h2>{user.name}</h2> </section> ); } function Page({id}) { // Start fetching the user data getUser(id); // ... some computational work return ( <> <Profile id={id} /> </> ); } ``` The Page component calls getUser without awaiting to kick off the async database query. While Page does other work and renders children, the fetch completes. When Profile renders and awaits getUser, the data is already cached.

Example: Share data snapshot between components

```js import {cache} from 'react'; import {fetchTemperature} from './api.js'; const getTemperature = cache(async (city) => { return await fetchTemperature(city); }); async function AnimatedWeatherCard({city}) { const temperature = await getTemperature(city); // ... } async function MinimalWeatherCard({city}) { const temperature = await getTemperature(city); // ... } ``` When both components render for the same city, they receive the same data snapshot from the cached function. If they receive different cities, fetchTemperature is called twice.

Pitfall: Different memoized functions have different caches

Calling cache() multiple times creates separate memoized functions with separate caches. To allow components to share cached results, they must call the same memoized function. The memoized function should be created once outside components and imported where needed, rather than calling cache() inside component functions.

cache() function signature and purpose

cache() is a React API that caches the result of a data fetch or computation. It is only for use with React Server Components. The signature is: const cachedFn = cache(fn). It takes a function fn that can take any arguments and return any value, and returns a cached version of fn with the same type signature.

Pitfall: Memoized functions outside components do not use cache

Calling a memoized function outside of a component will not use the cache. React only provides cache access to memoized functions when called within a component, because cache access is provided through React context which is only accessible from components.

cache() uses shallow equality for cache lookup

React uses shallow equality of arguments to determine if there is a cache hit via Object.is(). If arguments are not primitives (objects, functions, arrays), you must pass the same object reference to get a cache hit. Different object references with the same values will result in cache misses.

Example: Cache an expensive computation

```js 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); // ... } // ... } ``` This example shows how cache() allows two components to share work. If the same user object is rendered in both components, calculateUserMetrics is only called once.

Comparison: cache vs useMemo

useMemo should be used for caching expensive computations in Client Components across renders. Its cache is local to each component instance. cache() should be used in Server Components to memoize work that can be shared across components. cache() also supports data fetches, unlike useMemo. cache() is invalidated across server requests, while useMemo persists within a component across re-renders as long as dependencies don't change.

captureOwnerStack signature and return type

captureOwnerStack() is a function that takes no parameters and returns string | null. It reads the current Owner Stack in development and returns it as a string if available.

captureOwnerStack usage in custom error overlay

captureOwnerStack can enhance a custom error overlay by capturing the Owner Stack when console.error is called. Import captureOwnerStack from react, intercept console.error calls, and call captureOwnerStack within the error handler to include the owner stack information in error reporting.

captureOwnerStack only works in development

Owner Stacks are only available in development. captureOwnerStack will always return null outside of development, and is only exported in development builds. In production builds, captureOwnerStack will be undefined.

captureOwnerStack availability in different contexts

Owner Stacks are available in: component render, effects (e.g. useEffect), React event handlers (e.g. <button onClick={...} />), and React error handlers (onCaughtError, onRecoverableError, and onUncaughtError). If no Owner Stack is available, null is returned.

Owner Stack vs Component Stack difference

Owner Stack is different from Component Stack available in React error handlers like errorInfo.componentStack. Owner Stack only includes components that created nodes (not those that forwarded them), and omits DOM components and siblings. Component Stack includes all components in the render tree. For example, if App renders children without creating a node containing SubComponent itself, App does not appear in Owner Stack but appears in Component Stack.

How to conditionally use captureOwnerStack for dev/prod bundling

When captureOwnerStack is used in files bundled for both development and production, use a namespace import and access it conditionally: import * as React from 'react'; followed by if (process.env.NODE_ENV !== 'production') { const ownerStack = React.captureOwnerStack(); }. Do not use named imports of captureOwnerStack in files bundled for both dev and production, as it will be undefined in production.

captureOwnerStack unavailable in custom DOM event handlers

captureOwnerStack returns null when called from custom DOM event handlers added with addEventListener, setTimeout callbacks, or fetch callbacks. Owner Stack must be captured during render, Effects, React event handlers, or React error handlers. To capture the stack for use in a DOM event, call captureOwnerStack during an Effect and store the result.

Activity component purpose

The Activity component lets you hide and restore the UI and internal state of its children.

Profiler component purpose

The Profiler component measures rendering performance of a React tree programmatically.

Built-in React components list

React provides five built-in components: Fragment (or <> syntax), Profiler, Suspense, StrictMode, and Activity. Fragment groups multiple JSX nodes together. Profiler measures rendering performance programmatically. Suspense displays a fallback while child components are loading. StrictMode enables extra development-only checks for finding bugs. Activity hides and restores the UI and internal state of its children.

StrictMode component purpose

The StrictMode component enables extra development-only checks that help you find bugs early.

cloneElement alternative: render props pattern

Instead of cloneElement, accept a render prop like renderItem. The parent component receives renderItem as a prop and calls it for each item, passing necessary derived data as arguments. For example: <List items={products} renderItem={(product, isHighlighted) => <Row key={product.id} title={product.title} isHighlighted={isHighlighted} />} />. This makes data flow explicit and is the preferred pattern.

cloneElement alternative: context pattern

Use context to pass data instead of cloneElement. Call createContext to define a context, then wrap rendered items in a context provider. Child components can read the context with useContext. This coordinates logic between parent and child without requiring the parent to manipulate child props.

cloneElement children argument best practices

Only pass children as multiple arguments to cloneElement if they are all statically known, like cloneElement(element, null, child1, child2, child3). If children are dynamic, pass the entire array as the third argument: cloneElement(element, null, listItems). This ensures React will warn about missing keys for dynamic lists; for static lists this is not necessary.

cloneElement element parameter requirements

The element argument must be a valid React element. It can be a JSX node like <Something />, the result of calling createElement, or the result of another cloneElement call.

cloneElement pitfall: data flow complexity

Using cloneElement is uncommon and can lead to fragile code because it makes it harder to trace the data flow. Consider using alternatives like render props, context, or custom Hooks instead.

cloneElement signature and basic usage

cloneElement(element, props, ...children) creates a new React element using another element as a starting point. It takes an element as the first argument, optional props to override as the second argument, and optional children as remaining arguments. Example: const clonedElement = cloneElement(<Row title="Cabbage">Hello</Row>, { isHighlighted: true }, 'Goodbye') returns <Row title="Cabbage" isHighlighted={true}>Goodbye</Row>.

cloneElement alternative: custom Hook pattern

Extract non-visual logic into a custom Hook. For example, create useList(items) that returns [selected, onNext]. The parent component uses this Hook and passes the returned data to children as props. This makes data flow explicit and allows the logic to be reused across components.

cloneElement does not modify original element

Cloning an element does not modify the original element. A new element object is created with the specified modifications.

cloneElement return value properties

cloneElement returns a React element object with: type (same as element.type), props (shallow merge of element.props with overriding props), ref (original element.ref unless overridden by props.ref), and key (original element.key unless overridden by props.key). The element should typically be returned from a component or made a child of another element; treat every element as opaque after creation and only render it.

cloneElement children parameter handling

The optional ...children can be zero or more child nodes: React elements, strings, numbers, portals, empty nodes (null, undefined, true, false), or arrays of React nodes. If no ...children arguments are passed, the original element.props.children is preserved.

cloneElement props parameter behavior

The props argument must be an object or null. If null is passed, the cloned element retains all original element.props. If an object is passed, for every prop in the props object, the returned element prefers the value from props over element.props. The remaining props are filled from the original element.props. If props.key or props.ref are passed, they replace the original ones.

createContext must be called outside components

Call createContext outside of any components to create a context.

createContext return value

createContext returns a context object. The context object itself does not hold any information; it represents which context other components read or provide. The context object has properties: SomeContext (allows you to provide the context value to components), SomeContext.Consumer (a legacy rarely used way to read the context value), and SomeContext.Provider (a legacy way to provide the context value before React 19).

createContext function signature and parameters

createContext takes one parameter: defaultValue. The defaultValue is the value the context has when there is no matching context provider in the tree above the component reading the context. If there is no meaningful default value, specify null. The default value is static and never changes over time; it serves as a last resort fallback.

Importing and using exported context

// Button.js import { ThemeContext } from './Contexts.js'; function Button() { const theme = useContext(ThemeContext); // ... } // App.js import { ThemeContext, AuthContext } from './Contexts.js'; function App() { return ( <ThemeContext value={theme}> <AuthContext value={currentUser}> <Page /> </AuthContext> </ThemeContext> ); }

Exporting context from a file

// Contexts.js import { createContext } from 'react'; export const ThemeContext = createContext('light'); export const AuthContext = createContext(null);

Legacy SomeContext.Consumer pattern

function Button() { return ( <ThemeContext.Consumer> {theme => ( <button className={theme} /> )} </ThemeContext.Consumer> ); } This is a legacy way to read context. New code should use useContext() instead.

Context default value is not dynamic

The default value specified when creating a context (e.g., createContext('light')) never changes. React only uses this value as a fallback when it cannot find a matching provider above. To make context change over time, add state and wrap components in a context provider.

Reading context with useContext

function Button() { const theme = useContext(ThemeContext); return <button className={theme} />; } function Profile() { const currentUser = useContext(AuthContext); // ... }

Context provider with dynamic values example

function App() { const [theme, setTheme] = useState('dark'); const [currentUser, setCurrentUser] = useState({ name: 'Taylor' }); return ( <ThemeContext value={theme}> <AuthContext value={currentUser}> <Page /> </AuthContext> </ThemeContext> ); }

createContext basic example

import { createContext } from 'react'; const ThemeContext = createContext('light'); const AuthContext = createContext(null);

SomeContext.Consumer render function children

SomeContext.Consumer accepts a function as children. React calls this function with the current context value determined by the same algorithm as useContext() does, and renders the result. React re-runs this function and updates the UI whenever context from parent components changes. This is a legacy API; newly written code should use useContext() instead.

Context provider value prop

The value prop is passed to a context provider to specify the value that all components reading this context inside the provider will receive, no matter how deep. The context value can be of any type. A component calling useContext(SomeContext) inside the provider receives the value of the innermost corresponding context provider above it.

Context provider syntax in React 19

Starting in React 19, you can render SomeContext as a provider by wrapping components directly, for example: <ThemeContext value={theme}><Page /></ThemeContext>. In older versions of React, use <SomeContext.Provider> syntax instead.

createElement signature and basic usage

createElement is called with the signature createElement(type, props, ...children). It creates a React element with the given type, props, and children. The type argument must be a valid React component type, such as a tag name string like 'div' or 'span', or a React component (a function, a class, or a special component like Fragment). The props argument must either be an object or null; if null is passed, it will be treated as an empty object. Children are optional and can be zero or more React nodes, including React elements, strings, numbers, portals, empty nodes (null, undefined, true, false), and arrays of React nodes.

createElement return value properties

createElement returns a React element object with the following properties: type (the type you have passed), props (the props you have passed except for ref and key), ref (the ref you have passed, or null if missing), and key (the key you have passed, coerced to a string, or null if missing). The ref and key from the props object are special and will not be available as element.props.ref and element.props.key on the returned element, but instead as element.ref and element.key.

Give your agent this brain