1- import { useCallback , useEffect , useMemo , useState } from 'react' ;
1+ import { useCallback , useLayoutEffect , useMemo , useState } from 'react' ;
22import {
33 AMOUNT_INPUT_MAX_FONT_SIZE ,
44 AMOUNT_INPUT_POPUP_WIDTH ,
@@ -27,10 +27,11 @@ export type UseAmountInputFontSize = {
2727 * wide layouts such as the expanded view keep larger sizes while the popup
2828 * and side panel still step down.
2929 *
30- * One ResizeObserver per container supplies the width; nothing reads layout
31- * while typing. The width is stored rounded to a whole px and only when it
32- * changes, so resize notifications that do not move it cause no re-render.
33- * The font size itself is derived during render.
30+ * The width is read once before paint when the container mounts and then only
31+ * when a ResizeObserver reports a change, so typing never triggers a layout
32+ * read. The width is stored rounded to a whole px and only when it changes,
33+ * so resize notifications that do not move it cause no re-render. The font
34+ * size itself is derived during render.
3435 *
3536 * @param text - The amount as rendered, including any currency symbol.
3637 * @param options - Layout constraints of the input.
@@ -54,24 +55,35 @@ export function useAmountInputFontSize(
5455 setContainer ( element ) ;
5556 } , [ ] ) ;
5657
57- useEffect ( ( ) => {
58- if ( ! container || typeof ResizeObserver === 'undefined' ) {
58+ useLayoutEffect ( ( ) => {
59+ if ( ! container ) {
5960 return undefined ;
6061 }
6162 // React 18 can still run the component once for an update that bails
6263 // out, so repeats of the last reported width skip setState entirely.
6364 let lastReportedWidth : number | undefined ;
64- // The first notification arrives after layout and before paint.
65- const observer = new ResizeObserver ( ( [ entry ] ) => {
66- if ( ! entry ) {
65+ const reportWidth = ( width : number ) => {
66+ const rounded = Math . round ( width ) ;
67+ if ( rounded === lastReportedWidth ) {
6768 return ;
6869 }
69- const width = Math . round ( entry . contentRect . width ) ;
70- if ( width === lastReportedWidth ) {
70+ lastReportedWidth = rounded ;
71+ setMeasuredWidth ( ( previous ) =>
72+ previous === rounded ? previous : rounded ,
73+ ) ;
74+ } ;
75+ // Measure before paint so the first frame uses the real width. A
76+ // ResizeObserver created in useEffect would only fire after paint.
77+ reportWidth ( container . clientWidth ) ;
78+
79+ if ( typeof ResizeObserver === 'undefined' ) {
80+ return undefined ;
81+ }
82+ const observer = new ResizeObserver ( ( [ entry ] ) => {
83+ if ( ! entry ) {
7184 return ;
7285 }
73- lastReportedWidth = width ;
74- setMeasuredWidth ( ( previous ) => ( previous === width ? previous : width ) ) ;
86+ reportWidth ( entry . contentRect . width ) ;
7587 } ) ;
7688 observer . observe ( container ) ;
7789 return ( ) => observer . disconnect ( ) ;
0 commit comments