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 4 of 8.

createElement creates lightweight element descriptions, not DOM nodes

Creating a React element with createElement does not render the component or create any DOM elements. An element is a lightweight description or instruction for React to later render the component. Creating elements is extremely cheap and does not require optimization or avoidance.

createElement is alternative to JSX syntax

createElement serves as an alternative to writing JSX. Both createElement(Component, props) and <Component {...props} /> produce equivalent React element objects. Both coding styles are acceptable, with JSX being easier to visually match closing tags to opening tags.

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.

createElement immutability requirement

React elements and their props must be treated as immutable and never changed after creation. In development, React will freeze the returned element and its props property shallowly to enforce this.

createElement with custom components requires capital letters

When using createElement with custom components, pass the component function directly. A component name must start with a capital letter: createElement(Something) for custom components, whereas createElement('something') with a lowercase string is treated as a built-in HTML tag.

createRef example in class component

Example of declaring and using createRef in a class component: import { Component, createRef } from 'react'; export default class Form extends Component { inputRef = createRef(); handleClick = () => { this.inputRef.current.focus(); } render() { return ( <> <input ref={this.inputRef} /> <button onClick={this.handleClick}> Focus the input </button> </> ); } } This example shows declaring a ref as a class field and using it to access the input DOM node and call focus().

createRef is for class components

createRef is mostly used for class components. Function components typically rely on useRef instead.

createRef creates a new object on each call

createRef always returns a different object. It is equivalent to writing { current: null } yourself.

createRef signature and return value

createRef() takes no parameters and returns an object with a single property: current. Initially, current is set to null. If you pass the ref object to React as a ref attribute to a JSX node, React will set its current property.

useRef versus createRef equivalence

const ref = useRef() is equivalent to const [ref, _] = useState(() => createRef(null)). In a function component, useRef always returns the same object, whereas createRef returns a different object each time.

experimental_taintObjectReference parameters

message: The error message to display if the tainted object is passed to a Client Component; will be shown as part of the thrown Error. object: The object instance to be tainted; Functions and class instances can be passed, and React will replace its default error message with the provided message. When a specific instance of a Typed Array is passed, only that instance is tainted, not other copies.

experimental_taintObjectReference is Server Components only

experimental_taintObjectReference is only available inside React Server Components. It is part of the experimental API and requires react@experimental and react-dom@experimental packages.

experimental_taintObjectReference taints object instances not clones

Recreating or cloning a tainted object creates a new untainted object. For example, {name: user.name, ssn: user.ssn} or {...user} will create new objects that are not tainted. taintObjectReference only protects against simple mistakes when the exact object instance is passed unchanged to a Client Component.

experimental_taintObjectReference is not sufficient for security alone

Do not rely on taintObjectReference as the sole security mechanism. Cloning a tainted object creates an untainted copy, and derived values (e.g. {secret: taintedObj.secret}) create new untainted objects. Tainting is one layer of protection; secure applications require multiple layers of protection, well-designed APIs, and isolation patterns.

experimental_taintObjectReference prevents accidental data leaks

Call experimental_taintObjectReference in data fetching functions to prevent sensitive objects from being accidentally passed to Client Components. For example, taint a user object returned from a database query to catch mistakes during refactoring where the entire object might be passed to a Client Component instead of only specific properties.

experimental_taintObjectReference signature

experimental_taintObjectReference is called with two parameters: message (string for the error display) and object (the object instance to taint). It returns undefined. Example: experimental_taintObjectReference('Do not pass ALL environment variables to the client.', process.env)

experimental_taintUniqueValue function signature

The function signature is: taintUniqueValue(message, lifetime, value). It prevents unique values like passwords, keys, or tokens from being passed to Client Components. The function returns undefined.

experimental_taintUniqueValue parameters

Parameters: - message (string): The error message displayed if value is passed to a Client Component. - lifetime (object): Any object indicating how long value should be tainted. value is blocked from being sent to Client Components while this object exists. Examples: globalThis for app lifetime, or process object. Typically an object whose properties contain value. - value (string, bigint, or TypedArray): A unique sequence of characters or bytes with high entropy, such as a cryptographic token, private key, hash, or long password. This will be blocked from being sent to any Client Component.

experimental_taintUniqueValue is experimental API

This API is experimental and not available in a stable version of React yet. It is only available inside React Server Components. Users can try it by upgrading React packages to @experimental versions: react@experimental, react-dom@experimental, eslint-plugin-react-hooks@experimental.

taintUniqueValue does not protect derived values

Deriving new values from tainted values can compromise tainting protection. New values created by uppercasing tainted values, concatenating tainted strings, converting to base64, substringing tainted values, and other similar transformations are not automatically tainted. These derived values must be explicitly passed to taintUniqueValue to be tainted.

taintUniqueValue should not protect low-entropy values

Do not use taintUniqueValue to protect low-entropy values such as PIN codes or phone numbers. If any value in a request is controlled by an attacker, they could infer which value is tainted by enumerating all possible values of the secret.

taintUniqueValue example with environment variable

Example showing how to taint an API password: ```js 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 ); ``` This prevents the API password from being passed to Client Components or sent via Server Functions.

taintUniqueValue example with user session token

Example showing how to taint a user session token: ```js 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; } ``` The user object serves as the lifetime argument, ensuring the session token remains tainted for the lifetime of the user object.

taintUniqueValue tainting is not a complete security solution

Tainting a value does not block every possible derived value. Tainting only protects against simple mistakes like explicitly passing secret values to the client. Mistakes in calling taintUniqueValue (such as using a global store outside of React without the corresponding lifetime object) can cause tainted values to become untainted. A secure app requires multiple layers of protection, well designed APIs, and isolation patterns.

taintUniqueValue related to taintObjectReference

To prevent passing an object containing sensitive data, use taintObjectReference instead of taintUniqueValue. taintUniqueValue is specifically for unique values like passwords, keys, or tokens.

useSyncExternalStore hook

useSyncExternalStore lets a component subscribe to an external store. It is an Other Hook mostly useful to library authors and not commonly used in application code.

useReducer hook

useReducer declares a state variable with the update logic inside a reducer function. It is a State Hook used to add state to a component.

useContext hook

useContext reads and subscribes to a context. It is a Context Hook that lets a component receive information from distant parents without passing it as props.

useRef hook

useRef declares a ref. You can hold any value in it, but most often it is used to hold a DOM node. It is a Ref Hook that lets a component hold information that is not used for rendering.

useImperativeHandle hook

useImperativeHandle lets you customize the ref exposed by your component. This is rarely used and is a Ref Hook.

useEffect hook

useEffect connects a component to an external system. It is an Effect Hook that lets a component connect to and synchronize with external systems including network, browser DOM, animations, widgets written using a different UI library, and other non-React code. Effects are an escape hatch from the React paradigm and should not be used to orchestrate data flow of an application.

useLayoutEffect hook

useLayoutEffect fires before the browser repaints the screen. You can measure layout with useLayoutEffect. It is a rarely used variation of useEffect with differences in timing.

useInsertionEffect hook

useInsertionEffect fires before React makes changes to the DOM. Libraries can insert dynamic CSS with useInsertionEffect. It is a rarely used variation of useEffect with differences in timing.

useEffectEvent hook

useEffectEvent creates a non-reactive event to fire from any Effect hook. It lets you separate events from Effects.

useMemo hook

useMemo lets you cache the result of an expensive calculation. It is a Performance Hook used to optimize re-rendering by skipping unnecessary calculations.

useCallback hook

useCallback lets you cache a function definition before passing it down to an optimized component. It is a Performance Hook used to optimize re-rendering by skipping unnecessary work.

useTransition hook

useTransition lets you mark a state transition as non-blocking and allow other updates to interrupt it. It is a Performance Hook used to prioritize rendering by separating blocking updates from non-blocking updates.

useDeferredValue hook

useDeferredValue lets you defer updating a non-critical part of the UI and let other parts update first. It is a Performance Hook used to prioritize rendering.

useDebugValue hook

useDebugValue lets you customize the label React DevTools displays for your custom Hook. It is an Other Hook mostly useful to library authors and not commonly used in application code.

useId hook

useId lets a component associate a unique ID with itself. It is typically used with accessibility APIs and is an Other Hook mostly useful to library authors and not commonly used in application code.

Refs do not re-render

Unlike with state, updating a ref does not re-render your component. Refs are an escape hatch from the React paradigm.

useActionState hook

useActionState allows you to manage state of actions. It is an Other Hook mostly useful to library authors and not commonly used in application code.

useState hook

useState declares a state variable that you can update directly. It is a State Hook used to add state to a component.

Built-in Hooks can be combined into custom Hooks

You can define your own custom Hooks as JavaScript functions by combining built-in Hooks.

Effects are escape hatch from React paradigm

Effects are an escape hatch from the React paradigm. Do not use Effects to orchestrate the data flow of your application. If you are not interacting with an external system, you might not need an Effect.

Rules of React overview

React has three main rules or idioms: Components and Hooks must be pure to make code easier to understand and debug and allow React to optimize automatically, React calls Components and Hooks as React is responsible for rendering them when necessary to optimize user experience, and Rules of Hooks which restrict where hooks defined as JavaScript functions can be called.

React section content

The React section provides programmatic React features including Hooks for using different React features from components, Components as built-in components usable in JSX, APIs useful for defining components, and Directives providing instructions to bundlers compatible with React Server Components.

React reference documentation structure

The React reference documentation is organized into major sections: React (Hooks, Components, APIs, Directives), React DOM (Hooks, Components, APIs, Client APIs, Server APIs, Static APIs), React Compiler (Configuration, Directives, Compiling Libraries), ESLint Plugin React Hooks (Lints), Rules of React (purity, component calling, hook rules), and Legacy APIs.

What isValidElement returns false for

isValidElement returns false for: strings, numbers, null, undefined, plain objects, arrays, component constructors (like MyComponent without angle brackets), and portals created with createPortal.

What counts as a React element

React elements are values produced by writing JSX tags (like <p /> or <MyComponent />) or values produced by calling createElement(). Only JSX tags and objects returned by createElement are considered React elements.

React elements vs React nodes distinction

React elements are a subset of React nodes. A React node can be a React element, a portal, a string, a number, true, false, null, undefined, or an array of React nodes. isValidElement only checks for React elements, not all valid React nodes. For example, 42 is a valid React node but not a valid React element.

isValidElement usage example

Example showing what isValidElement identifies as React elements and what it does not: ```js import { isValidElement, createElement } from 'react'; // ✅ React elements console.log(isValidElement(<p />)); // true console.log(isValidElement(createElement('p'))); // true console.log(isValidElement(<MyComponent />)); // true console.log(isValidElement(createElement(MyComponent))); // true // ❌ Not React elements console.log(isValidElement(null)); // false console.log(isValidElement(25)); // false console.log(isValidElement('Hello')); // false console.log(isValidElement({ age: 42 })); // false console.log(isValidElement([<div />, <div />])); // false console.log(isValidElement(MyComponent)); // false ```

When to use isValidElement

isValidElement is mostly useful when calling another API that only accepts elements (like cloneElement) and you want to avoid an error when your argument is not a React element. It is uncommon to need isValidElement, and you should avoid using it as a way to check whether something can be rendered.

forwardRef render function parameters

The render function passed to forwardRef receives two parameters: props (the props passed by the parent component) and ref (the ref attribute passed by the parent component). The ref can be an object or a function, and will be null if the parent component has not passed a ref. The render function should either pass the ref to another component or pass it to useImperativeHandle.

forwardRef in Strict Mode calls render function twice

In Strict Mode, React will call the render function passed to forwardRef twice in development only to help find accidental impurities. This does not affect production. If the render function is pure as it should be, this should not affect the logic of the component. The result from one of the calls will be ignored.

forwardRef example: expose DOM node to parent

To expose a DOM node to a parent component, wrap the component definition with forwardRef, receive the ref as the second parameter, and pass it to the DOM node you want to expose. Example: const MyInput = forwardRef(function MyInput(props, ref) { const { label, ...otherProps } = props; return (<label>{label}<input {...otherProps} ref={ref} /></label>); });

forwardRef example: playing and pausing a video

Example of using forwardRef to control video playback from a parent component: const VideoPlayer = forwardRef(function VideoPlayer({ src, type, width }, ref) { return ( <video width={width} ref={ref}> <source src={src} type={type} /> </video> ); }); function App() { const ref = useRef(null); return ( <> <button onClick={() => ref.current.play()}>Play</button> <button onClick={() => ref.current.pause()}>Pause</button> <MyVideoPlayer ref={ref} src="..." type="video/mp4" width="250" /> </> ); }

forwardRef example: focusing a text input

Example showing how to use forwardRef to focus a text input from a parent component: const MyInput = forwardRef(function MyInput(props, ref) { const { label, ...otherProps } = props; return ( <label> {label} <input {...otherProps} ref={ref} /> </label> ); }); function Form() { const ref = useRef(null); function handleClick() { ref.current.focus(); } return ( <form> <MyInput label="Enter your name:" ref={ref} /> <button type="button" onClick={handleClick}>Edit</button> </form> ); }

forwardRef typical use case: reusable low-level components

Exposing refs to DOM nodes is typically done for reusable low-level components like buttons or text inputs. It is not recommended to expose refs for application-level components like avatars or comments, as this makes it harder to change the component's internals later.

Give your agent this brain