Skip to content

useFieldContext reactivity broken by React Compiler and ternary operator #1832

Closed

Description

@JamesHyot

Describe the bug

When using useFieldContext with React Compiler and a ternary expression to render or not an input, the reactivity of the field breaks and its values is not updated when typing.

This is caused by the Compiler changing the dependency for a rerender from "field.state.value" to "field", which is always the same object so no UI update is made.
I have no idea if this is really an issue with @tanstack/form or the React Compiler itself, though I can get why the compiler would want to memo based on "field" and not only its subproperties.

This example doesn't work (and neither does a {canBeExtended && (<input value={field.state.value} onChange={(e) => field.handleChange(e.target.value)} />)} :

import { useFieldContext } from './form-context.tsx'

export function TextField({ label, canBeExtended }: { label: string, canBeExtended: boolean }) {
  // The `Field` infers that it should have a `value` type of `string`
  const field = useFieldContext<string>()
  return (
    <label>
      <span>{label}</span>
			{canBeExtended ?
				(<input
					value={field.state.value}
					onChange={(e) => field.handleChange(e.target.value)}
					/>)
				: (<div className='extended'>
					<input
						value={field.state.value}
						onChange={(e) => field.handleChange(e.target.value)}
					/>
				</div>)}
    </label>
  )
}

See the Compiler playground which outputs an if ($[2] !== canBeExtended || $[3] !== field) { which is different from the if ($[4] !== field.state.value || $[5] !== t2) { of this basic playground

There are several workarounds available to us, destructuring field, writing the ternary expression another way, or using a temp variable : "const val = field.state.value". However this issue caught me off-guard so I decided to submit it.

Your minimal, reproducible example

https://playground.react.dev/#N4Igzg9grgTgxgUxALhASwLYAcIwC4AEwBUYCAYmggDYAmAwhAHZ4IAehAvgQGYwQYCAcgB0Aeh64MAWjjNWHEXjBshAHSYb2OfLyhM4eNMwIAVdnko1aACmLUAhgCMaAGgJwHTAEIIAohwITLQItAScyEQEji7UkWB4MGhMAObunj7+gcGhkU4QENQIXuEAlEQaBARiYmYAFggEAAZWdE0EyTwIMGAEeHUOhGiEYHXQdAQDAG6NDs1TDtRQCO14AJ5YjRA8zQlJqU2VHswJvFQTALwkZK0M8hYAPHvJKQB8NqVHMAh4sEwENiOVQeMRoryBVQITywXlewFB1E4DzEYBhTHBmjwaixeGAGV8AVYOTCAH4NNiKTibA9klgoFjMZTKQslggLsAeOdaCIEoMECIWctOOScUy8Mx6ANUmzgDYEOULq8ztYRFLaEVJV4Ugg5UoHDBtXgBYtlqVhYzRTixK9PhbKZFqbQ0FMPI4wGAAHIODBsoQWIIhWhCDFiyk0ph0hmhy2CmWclW81jG1nm6OUiVS7XsuUKpXxuiqrzqhCa6W6vD6w3J02py2U60isXIp1TG3myFQsQIjFVW2cECuEByJiclIodDYXCEdabKIABSWKWSAHksEYTuFePxBEInM4aNIsIvktJvg5DLIBFg0EUYGInQkhABuclMOxHGpybA3wbGJgAWQgEJIjUEBFmoUCNG4MBfzAeNegXKAlyYVd1yYMBSifAdwDGAB3ABJFhuiYRYwBQHhSIQTggA

Steps to reproduce

Create a pre-bound field component which renders an input conditionnally
Add React Compiler
The field doesn't update :(

Expected behavior

The input should update when you type something in it

How often does this bug happen?

None

Screenshots or Videos

No response

Platform

Not OS or Browser specific

TanStack Form adapter

react-form

TanStack Form version

1.19.1

TypeScript version

5.9.2

Additional context

No response

Activity

  1. LeCarbonator commented on Oct 30, 2025

    @LeCarbonator
    Contributor

    I have no idea if this is really an issue with @tanstack/form or the React Compiler itself, though I can get why the compiler would want to memo based on "field" and not only its subproperties.

    What happens if you use the explicitly reactive variants of all accessors?

    const value = useStore(field.store, state => state.value);

    The hook should cause a rerender on value change already, but perhaps this can help with figuring out the problem.

  2. JamesHyot commented on Oct 30, 2025

    @JamesHyot
    Author

    This does make the input reactive again, but so did this :

      const field = useFieldContext<string>()
      const value = field.state.value
      return (
        <label>
          <span>{label}</span>
    			{canBeExtended && <input
    				value={value}
    				onChange={(e) => field.handleChange(e.target.value)}
    			/>
    			}
        </label>
      )

    or this :

      const { handleChange, value } = useFieldContext<string>()
    
      return (
        <label>
          <span>{label}</span>
    			{canBeExtended && <input
    				value={value}
    				onChange={(e) => handleChange(e.target.value)}
    			/>
    			}
        </label>
      )

    Because the docs do use const field = useFieldContext<string>() and then access its properties in the rest of the components, I didn't think using field directly could cause any issue

  3. LeCarbonator commented on Oct 30, 2025

    @LeCarbonator
    Contributor

    The field itself is (mostly) stable. field.state is a getter of the current values, and it's set to rerender everytime values changes. However, that value rerender does not change the reference of field, so it seems like it was wrongly optimized away

  4. crutchcorn commented on Dec 1, 2025

    @crutchcorn
    Contributor

    @JamesHyot can you share a full reproduction with us in the form of a StackBlitz or Codesandbox? I think I have a fix.

  5. elliason commented on Dec 1, 2025

    @elliason

    I am also having troubles with stale field.state.value. What I do is getting the field context in one component:

    export const PreBoundDateField = ({ label }: { label: string }) => {
        const field = useFieldContext<string>();
    
        console.log('PreBoundDateField - field.state.value', field.state.value);
    
        return <DateField field={field} label={label} />;
    };
    

    Then passing it to another component:

    export const DateField = ({ field, label }: { field: AnyFieldApi; label: string }) => {
        const fieldState = field.state;
        const fieldValue = fieldState.value ?? '';
    
        console.log('DateField - selectedDate', selectedDate);
    
        return (
            <div>
                <Label htmlFor={field.name}>{label}</Label>
                <DatePicker
                    id={field.name}
                    value={fieldValue}
                    onDateChange={field.handleChange}
                    onBlur={field.handleBlur}
                    placeholder="Select a date"
                />
                <FieldInfo errorID={errorID} fieldState={fieldState} />
            </div>
        );
    };
    

    While the log in PreBoundDateField where field is returned from context shows the correct value, in DateField the value is stale and does not update.

    @crutchcorn Would the PR above also fix this, or is this unrelated problem ? Thanks

  6. crutchcorn commented on Dec 1, 2025

    @crutchcorn
    Contributor

    I think it should!

    Can you test your code against this PR?

    #1893

    npm i https://pkg.pr.new/@tanstack/react-form@1893
    

    And let me know? If not, please open a new issue and include a StackBlitz/Codesandbox

  7. elliason commented on Dec 1, 2025

    @elliason

    I will try, thank you!

  8. elliason commented on Dec 1, 2025

    @elliason

    🚀🔥 YES! Confirmed, It works great! Thank you very much!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions