Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/fix-fieldset-rerender-loop.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@ark-ui/react': patch
---

Fix `Fieldset.Root` re-rendering whenever its subtree mutated, even if helper and error text were unchanged. A nested
`Field.Textarea` with `defaultValue` could turn that into a loop that froze the tab.
26 changes: 26 additions & 0 deletions packages/react/src/components/fieldset/fieldset.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -75,4 +75,30 @@ describe('Fieldset', () => {
expect(describedBy).toContain('helper-text')
})
})

it('should not re-render in a loop when a textarea with defaultValue is nested', () => {
let renders = 0

render(
<Fieldset.Root>
<Fieldset.Legend>Legend</Fieldset.Legend>
<Field.Root>
<Field.Label>Summary</Field.Label>
<Field.Textarea defaultValue="hello" />
</Field.Root>
<Fieldset.Context>
{() => {
renders += 1
if (renders > 50) {
throw new Error('Fieldset entered an update loop')
}
return null
}}
</Fieldset.Context>
</Fieldset.Root>,
)

expect(screen.getByRole('textbox')).toHaveValue('hello')
expect(renders).toBeLessThan(10)
})
})
12 changes: 6 additions & 6 deletions packages/react/src/components/fieldset/use-fieldset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ export const useFieldset = (props: UseFieldsetProps = {}) => {

const env = useEnvironmentContext()

const [textElements, setTextElements] = useState({ hasErrorText: false, hasHelperText: false })
const [hasErrorText, setHasErrorText] = useState(false)
const [hasHelperText, setHasHelperText] = useState(false)

const uid = useId()
const id = props.id ?? uid
Expand All @@ -45,9 +46,8 @@ export const useFieldset = (props: UseFieldsetProps = {}) => {

const checkTextElements = () => {
const docOrShadowRoot = env.getRootNode() as ShadowRoot | Document
const hasErrorText = !!docOrShadowRoot.getElementById(errorTextId)
const hasHelperText = !!docOrShadowRoot.getElementById(helperTextId)
setTextElements({ hasErrorText, hasHelperText })
setHasErrorText(!!docOrShadowRoot.getElementById(errorTextId))
setHasHelperText(!!docOrShadowRoot.getElementById(helperTextId))
}

checkTextElements()
Expand All @@ -60,8 +60,8 @@ export const useFieldset = (props: UseFieldsetProps = {}) => {
}, [env, errorTextId, helperTextId])

const ids: string[] = []
if (textElements.hasErrorText && invalid) ids.push(errorTextId)
if (textElements.hasHelperText) ids.push(helperTextId)
if (hasErrorText && invalid) ids.push(errorTextId)
if (hasHelperText) ids.push(helperTextId)
const labelIds = ids.length > 0 ? ids.join(' ') : undefined

const getRootProps = () =>
Expand Down