Skip to content
Source
Sign inSign up
TanStack/form

Reusable app hooks #1179

Mergedcrutchcorn(GitHub profile, opens in a new tab)merged 23 commits intomain fromrefs/pull/1179/headmerged by crutchcorn(GitHub profile, opens in a new tab)

This has been cooking in the oven for a long time - I'm extremely sorry it took me so long to figure out the direction we wanted to go in.

This PR introduces three new APIs to help with:

  • Form composability
  • UI component binding
  • form.Field boilerplate

All without having to type cast any generic by hand.

The API, for React, is as such:


// /src/hooks/form.ts, to be used across the entire app
const { fieldContext, useFieldContext, formContext, useFormContext } =
  createFormHookContexts()

function TextField({ label }: { label: string }) {
  const field = useFieldContext<string>()
  return (
    <label>
      <div>{label}</div>
      <input
        value={field.state.value}
        onChange={(e) => field.handleChange(e.target.value)}
      />
    </label>
  )
}

function SubscribeButton({ label }: { label: string }) {
  const form = useFormContext()
  return (
    <form.Subscribe selector={(state) => state.isSubmitting}>
      {(isSubmitting) => <button disabled={isSubmitting}>{label}</button>}
    </form.Subscribe>
  )
}

const { useAppForm, withForm } = createFormHook({
  fieldComponents: {
    TextField,
  },
  formComponents: {
    SubscribeButton,
  },
  fieldContext,
  formContext,
})

// /src/features/people/shared-form.ts, to be used across `people` features
const formOpts = formOptions({
  defaultValues: {
    firstName: 'John',
    lastName: 'Doe',
  },
})

// /src/features/people/nested-form.ts, to be used in the `people` page
const ChildForm = withForm({
  ...formOpts,
  // Optional, but adds props to the `render` function outside of `form`
  props: {
    title: 'Child Form',
  },
  render: ({ form, title }) => {
    return (
      <div>
        <p>{title}</p>
        <form.AppField
          name="firstName"
          children={(field) => <field.TextField label="First Name" />}
        />
        <form.AppForm>
            <form.SubscribeButton label="Submit" />
        </form.AppForm>
      </div>
    )
  },
})

// /src/features/people/page.ts
const Parent = () => {
  const form = useAppForm({
    ...formOpts,
  })

  return <ChildForm form={form} title={'Testing'} />
}

TODO

  • Confirm this doesn't break React Compiler usage
  • Gather feedback from other maintainers on withField and useAppForm API
  • Port this API (or similar) to other frameworks
    • May be delayed until after v1
  • Write docs

Notes

This PR supersedes #583, #825, and #1084

    1. View your CI Pipeline Execution ↗ for commit 7d9300e6af58a8bcfb9492fe9fa3869d84ce2629.

      CommandStatusDurationResult
      nx affected --targets=test:sherif,test:knip,tes...✅ Succeeded54sView ↗
      nx run-many --target=build --exclude=examples/**✅ Succeeded<1sView ↗

      ☁️ Nx Cloud last updated this comment at 2025-03-01 06:04:33 UTC

    2. Codecov Report

      Attention: Patch coverage is 93.54839% with 2 lines in your changes missing coverage. Please review.

      Project coverage is 88.62%. Comparing base (bea5803) to head (7d9300e). Report is 2 commits behind head on main.

      Files with missing linesPatch %Lines
      packages/react-form/src/createFormHook.tsx93.33%2 Missing :warning:
      Additional details and impacted files
      @@            Coverage Diff             @@
      ##             main    #1179      +/-   ##
      ==========================================
      + Coverage   88.50%   88.62%   +0.11%     
      ==========================================
        Files          27       28       +1     
        Lines        1218     1248      +30     
        Branches      322      325       +3     
      ==========================================
      + Hits         1078     1106      +28     
      - Misses        125      127       +2     
        Partials       15       15              

      :umbrella: View full report in Codecov by Sentry. :loudspeaker: Have feedback on the report? Share it here.

    3. There are scenarios where you do not care about the field values and only require access to things like ìsDirty, isSubmitting etc.

      Could you look into adding a formComponents API?

      Consider the following use case:

      // FormPromptUnsaved.tsx
      export const FormPromptUnsaved = withForm({
        defaultValues: {} as unknown,
        props: {} as {
           when?: (isDirty: boolean) => boolean;
        },
        render: props => (
          <props.form.Subscribe selector={state => [state.isDirty, state.isSubmitted]}>
            {([isDirty, isSubmitted]) => (
              <PromptUnsavedComponent
                isDirty={isDirty}
                isSubmitted={isSubmitted}
                when={props.when}
              />
            )}
          </props.form.Subscribe>
        ),
      });
      
      // main.tsx
      
      // cannot be assigned, validators differ
      <FormPromptUnsaved when={(isDirty) => isDirty || hasDifferentOrder} form={myAppForm} />
    4. Agreed @LeCarbonator. The idea will be that if you need to use form.Subscribe then you can use formComponents, but if you're using form.Field you can use fieldComponents. Something like this:

      ---
      config:
          look: handDrawn
      ---
      flowchart TD
          A["Do you need to reuse state (like defaultValues)?"]
          A -- Yes --> B["Use 'formOptions()'"]
          A -- No --> C["Do you need to reuse custom validation functions?"]
          C -- Yes --> D["Wrap 'useForm' hook into a custom app hook"]
          C -- No --> E["Do you need to reuse custom UI components?"]
          E -- Yes --> F["Do you need access to the 'field'?"]
          F -- Yes --> G["Use 'createFormHook''s 'fieldComponents'<br/>(EG: 'TextInput' and 'NumberInput')"]
          F -- No --> H["Use 'createFormHook''s 'formComponents'<br/>(EG: 'SubmitButton')"]
          E -- No --> I["Do you need to reuse whole subsections of your form?"]
          I -- Yes --> J["Use 'withForm' from 'createFormHook'"]
          I -- No --> K["Use 'form.Subscribe' and 'form.Field'"]
    5. @crutchcorn do these new patterns/api impact performance of fields. Unnecessary rerenderings because of the context?

    6. @crutchcorn do these new patterns/api impact performance of fields. Unnecessary rerenderings because of the context?

      Good question! They shouldn't, because the values passed into the contexts aren't reactive and are powered by TanStack Store to be reactive on a fine-grained level ala signals.

    7. Please add the following section to the documentation about withForm():

      Eslint's Rules of Hooks plugin has a rule that checks for React hooks being used outside of components (or other hooks). This check is surface level, but it does care about the way the function is written:

      • Must be named
      • Start with an upper case letter (MyComponent)
      • Start with use (useCustomHook)

      This means that to avoid this ESLint complaint, you have to use the following structure:

      withForm({
        ...formOpts,
        render: (props) => {
          // ESLint: useState must be used in a component or hook
          const [enabled, setEnabled] = useState(true); 
        },
      })
      withForm({
        ...formOpts,
        render: function Render(props) {
          // No ESLint error
          const [enabled, setEnabled] = useState(true); 
        },
      })
    8. Just minor suggestions and some typos. Looks good to me otherwise!

      Note: This review only addresses the docs. I have not reviewed the code changes.

      Resolvedby crutchcorn(GitHub profile, opens in a new tab)
      OutdatedResolvedby crutchcorn(GitHub profile, opens in a new tab)
      Resolvedby crutchcorn(GitHub profile, opens in a new tab)
      OutdatedResolvedby crutchcorn(GitHub profile, opens in a new tab)
      Resolvedby crutchcorn(GitHub profile, opens in a new tab)

Sign in to join this conversation.