Skip to content
Source
Sign inSign up
TanStack/form
Open History to see the last commit

reactivity.md

52 lines2.3 KB

1---
2id: reactivity
3title: Reactivity
4---
5​
6Tanstack Form doesn't cause re-renders when interacting with the form. So, you might find yourself trying to use a form or field state value without success.
7​
8If you would like to access reactive values, you will need to subscribe to them using one of two methods: `useStore` or the `form.Subscribe` component.
9​
10Some uses for these subscriptions are rendering up-to-date field values, determining what to render based on a condition, or using field values inside the logic of your component.
11​
12> For situations where you want to "react" to triggers, check out the [listener](./listeners.md) API.
13​
14## useStore
15​
16The `useStore` hook is perfect when you need to access form values within the logic of your component. `useStore` takes two parameters. First, the form store. Second, a selector to specify the piece of the form you wish to subscribe to.
17​
18```tsx
19const firstName = useStore(form.store, (state) => state.values.firstName)
20const errors = useStore(form.store, (state) => state.errorMap)
21```
22​
23You can access any piece of the form state in the selector.
24​
25> Note, that `useStore` will cause a whole component re-render whenever the value subscribed to changes.
26​
27While it IS possible to omit the selector, resist the urge as omitting it would result in many unnecessary re-renders whenever any of the form state changes.
28​
29## form.Subscribe
30​
31The `form.Subscribe` component is best suited when you need to react to something within the UI of your component. For example, showing or hiding UI based on the value of a form field.
32​
33```tsx
34<form.Subscribe
35 selector={(state) => state.values.firstName}
36 children={(firstName) => (
37 <form.Field>
38 {(field) => (
39 <input
40 name="lastName"
41 value={field.state.lastName}
42 onChange={field.handleChange}
43 />
44 )}
45 </form.Field>
46 )}
47/>
48```
49​
50> The `form.Subscribe` component doesn't trigger component-level re-renders. Anytime the value subscribed to changes, only the `form.Subscribe` component re-renders.
51​
52The choice between whether to use `useStore` or `form.Subscribe` mainly boils down to your use case. If you're aiming for direct UI updates based on form state, use `form.Subscribe` for its optimization perks. And if you need the reactivity within the logic, then `useStore` is the better choice.