React & Modern Frontend (445 Qs)•Part 11: Legacy Architecture, Migration Patterns & Historical Internals (354 - 445)
Why do you need additional care for component libraries while using forward refs?
When you start using forwardRef in a component library, you should treat it as a breaking change and release a new major version of your library. This is because your library likely has a different behavior such as what refs get assigned to, and what types are exported. These changes can break apps and other libraries that depend on the old behavior.
Code Example
tsx
import React, { forwardRef } from 'react';
// In a published UI library, modifying ref target is a BREAKING CHANGE:
// Version 1.0: forwarded ref points to outer <div> container
// Version 2.0: forwarded ref points to inner <input>
// Consumers relying on div-specific properties (e.g. clientWidth, style) will break!
export const LibraryButton = forwardRef<HTMLButtonElement, { label: string }>(
(props, ref) => {
return (
<button ref={ref} className="px-4 py-2 bg-indigo-600 text-white rounded">
{props.label}
</button>
);
}
);