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

refs & forward refs

18 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

useRef Hook basic usage

Import useRef from 'react'. Call useRef(null) to declare a ref inside a component. This returns an object with a single property called current. Initially, ref.current will be null. When React creates a DOM node for the element with ref attribute, React puts a reference to that node into ref.current.

Passing ref as JSX attribute

Pass a ref as the ref attribute to a JSX tag to get access to the underlying DOM node. Example: <div ref={myRef}> will set myRef.current to the div DOM element.

Accessing DOM nodes via ref.current

After a ref is attached to a DOM element, you can access the element from event handlers and use built-in browser APIs defined on it. Example: myRef.current.scrollIntoView() or myRef.current.focus().

ref callback for dynamic lists

Instead of calling useRef in a loop (which violates hook rules), pass a function to the ref attribute. This ref callback receives the DOM node when it's time to set the ref, and receives null when it's time to clear it. Return a cleanup function from the callback to remove the ref. This allows managing a Map or array of refs for list items.

ref callback with cleanup function

A ref callback can return a cleanup function: ref={(node) => { doSomething(node); return () => { cleanup(); }; }} React will call the cleanup function when clearing the ref.

Ref callback runs twice in Strict Mode

When Strict Mode is enabled, ref callbacks will run twice in development. This helps find bugs in callback refs by testing if the code handles being called multiple times.

Passing refs to child components

You can pass refs from a parent component to child components just like any other prop. A ref created in the parent can be passed to a child component, which then attaches it to a DOM element. This gives the parent access to that DOM node.

useImperativeHandle to restrict exposed API

Use useImperativeHandle to restrict which methods/properties of a DOM node are exposed through a ref. Instead of exposing the entire DOM element, you can create a custom object with only specific methods. Example: useImperativeHandle(ref, () => ({ focus() { realInputRef.current.focus(); } })) will only expose focus and nothing else.

When React attaches and clears refs

React sets ref.current during the commit phase, after the DOM is updated. During render, the DOM nodes have not been created yet, so ref.current is null. Before updating the DOM, React sets affected ref.current values to null. After updating the DOM, React immediately sets them to the corresponding DOM nodes.

Access refs from event handlers

Usually access refs from event handlers. If you need to do something with a ref but there is no particular event, you might need an Effect.

Avoid modifying DOM managed by React

Refs are an escape hatch. Avoid changing DOM nodes managed by React by manually modifying, adding children, or removing children from elements managed by React. This can lead to inconsistent visual results or crashes. Modifying DOM nodes changes the state that React knows about, causing React to become out of sync.

Safe DOM modification for unmanaged areas

You can safely modify parts of the DOM that React has no reason to update. For example, if a <div> is always empty in JSX, React will not touch its children list, so it is safe to manually add or remove elements there.

Refs as non-destructive escape hatches

Common non-destructive use cases for refs include managing focus, scroll position, and calling browser APIs that React does not expose. These actions don't conflict with React's internal state and are safe to use.

Example: Focus text input with useRef

import { useRef } from 'react'; export default function Form() { const inputRef = useRef(null); function handleClick() { inputRef.current.focus(); } return ( <> <input ref={inputRef} /> <button onClick={handleClick}> Focus the input </button> </> ); }

Example: Multiple refs for scrolling carousel

You can have multiple refs in a component. Use them to reference different DOM elements and call methods like scrollIntoView() on them. Example: firstCatRef.current.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'center' })

Example: Ref callback with Map for dynamic lists

const itemsRef = useRef(null); function getMap() { if (!itemsRef.current) { itemsRef.current = new Map(); } return itemsRef.current; } // In render: <li ref={(node) => { const map = getMap(); map.set(cat, node); return () => { map.delete(cat); }; }} > This pattern stores refs to list items in a Map, allowing access to any item by its ID without calling useRef in a loop.

Example: useImperativeHandle limiting exposed API

import { useRef, useImperativeHandle } from 'react'; function MyInput({ ref }) { const realInputRef = useRef(null); useImperativeHandle(ref, () => ({ focus() { realInputRef.current.focus(); }, })); return <input ref={realInputRef} />; } This exposes only focus on the ref, hiding all other properties of the input element.

Refs hold any values, not just DOM nodes

While refs are most commonly used to hold DOM elements, they can hold any values. For example, a ref can hold a Map, a timer ID, or any other JavaScript value. This makes refs useful for storing values that need to persist across renders without triggering re-renders.

Give your agent this brain