{"id":11758,"library":"react-multi-ref","title":"React Multi-Ref Utility","description":"react-multi-ref is a lightweight utility library designed to simplify managing references to multiple, dynamically created React elements. It addresses a common challenge in React development where developers need to collect and interact with a collection of DOM nodes or component instances, especially when dealing with lists or forms. The current stable version is 1.0.2, indicating a mature and stable API. As a utility, its release cadence is likely slow, focusing on stability rather than frequent feature additions. Key differentiators include its simplicity, providing a `Map`-like interface to access refs by a custom key, and its explicit support for both functional components (via `useState`) and class components, with integrated TypeScript and Flow type definitions for enhanced developer experience. It avoids the complexities of managing arrays of refs manually or relying on less explicit methods.","status":"active","version":"1.0.2","language":"javascript","source_language":"en","source_url":"https://github.com/Macil/react-multi-ref","tags":["javascript","react","ref"],"install":[{"cmd":"npm install react-multi-ref","lang":"bash","label":"npm"},{"cmd":"yarn add react-multi-ref","lang":"bash","label":"yarn"},{"cmd":"pnpm add react-multi-ref","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"This package uses a default export for the MultiRef class. For CommonJS, `require('react-multi-ref')` directly returns the class.","wrong":"const MultiRef = require('react-multi-ref').MultiRef;","symbol":"MultiRef","correct":"import MultiRef from 'react-multi-ref';"},{"note":"When using in function components, create the MultiRef instance using `useState` with a factory function to ensure it persists across renders and avoids React's potential memory resets, unlike `useMemo`.","wrong":"const itemRefs = useMemo(() => new MultiRef(), []);","symbol":"MultiRef instance","correct":"const [itemRefs] = useState(() => new MultiRef());"},{"note":"The `ref` method requires a unique key parameter to associate the DOM element with that key in the internal map.","wrong":"<input ref={itemRefs.ref} />","symbol":"ref callback","correct":"<input ref={itemRefs.ref(i)} />"}],"quickstart":{"code":"import { useState } from 'react';\nimport MultiRef from 'react-multi-ref';\n\nfunction MyDynamicForm() {\n  // Initialize MultiRef using useState to persist the instance across renders\n  const [inputRefs] = useState(() => new MultiRef());\n\n  // Generate 5 input fields, assigning a ref to each using its index as a key\n  const inputElements = new Array(5).fill(null).map((_, i) => (\n    <div key={i} style={{ marginBottom: '10px' }}>\n      <label>\n        Input {i + 1}: \n        <input type=\"text\" ref={inputRefs.ref(i)} placeholder={`Value for item ${i + 1}`} />\n      </label>\n    </div>\n  ));\n\n  // Event handler to collect all input values\n  function handleSubmit() {\n    const values = [];\n    inputRefs.map.forEach((inputElement, key) => {\n      if (inputElement) {\n        values.push(`Key ${key}: ${inputElement.value}`);\n      }\n    });\n    alert(\"Current input values:\\n\" + values.join('\\n'));\n  }\n\n  return (\n    <div>\n      <h3>Dynamic Input Form</h3>\n      {inputElements}\n      <button onClick={handleSubmit} style={{ marginTop: '20px', padding: '10px 15px' }}>\n        Get All Input Values\n      </button>\n    </div>\n  );\n}\n\n// To run this example in a React application:\n// export default MyDynamicForm;","lang":"typescript","description":"Demonstrates how to use MultiRef in a functional React component to manage references to multiple dynamically created input elements and retrieve their values."},"warnings":[{"fix":"Always initialize `MultiRef` inside `useState`'s factory function: `const [myRefs] = useState(() => new MultiRef());`","message":"When using `react-multi-ref` in functional components, the `MultiRef` instance must be created and persisted using `useState` (e.g., `useState(() => new MultiRef())`). Do not use `useMemo` for this purpose, as React is allowed to reset memoized values at any time, which would lead to loss of ref tracking.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Ensure that the key passed to `multiRef.ref(key)` is unique for each element you want to track, typically derived from an array index or unique item ID.","message":"Each call to `multiRef.ref(key)` requires a unique `key` parameter. This key is used to identify and retrieve the specific element from the internal `Map`. Reusing the same key for different elements or omitting the key will lead to incorrect ref mapping.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Always check if the ref element exists before accessing its properties: `if (inputElement) { /* access inputElement.value */ }`. Ensure the component is mounted when accessing refs, e.g., in an `useEffect` or event handler, not during render.","cause":"Attempting to access properties (like `.value`) on a ref that has not yet been assigned by React, or refers to an unmounted component, or the `key` used in `multiRef.ref(key)` does not correspond to an actual mounted element.","error":"TypeError: Cannot read properties of undefined (reading 'value') or TypeError: Cannot read properties of null (reading 'value')"},{"fix":"Ensure `useState(() => new MultiRef())` is called directly within the body of your functional React component, not within any nested functions or event handlers.","cause":"Misuse of `useState` by calling it inside a non-component function or an event handler, instead of at the top level of a functional component.","error":"React Hook 'useState' cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function."}],"ecosystem":"npm"}