Skip to content

Commit a9c5335

Browse files
authored
docs: add gotcha on controlled inputs and cursor position without sync: true (#1182)
1 parent 4b8a5fe commit a9c5335

1 file changed

Lines changed: 27 additions & 0 deletions

File tree

docs/how-tos/some-gotchas.mdx

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,33 @@ subscribe(state.subscribeData, async () => {
148148
})
149149
```
150150

151+
## Controlled inputs may lose caret position without `sync: true`
152+
153+
Ref: https://github.com/pmndrs/valtio/issues/270
154+
155+
When using Valtio state with controlled `<input>` elements, you might notice the text caret jumping to the end while typing in the middle of the existing text.
156+
157+
This happens because Valtio batches state updates causing React to re-render after the input event. React resets the DOM value and loses the caret position.
158+
159+
**Use `{ sync: true }` to update synchronously and preserve the caret:**
160+
161+
```jsx
162+
function Input() {
163+
const snap = useSnapshot(state, { sync: true })
164+
165+
return (
166+
<input
167+
value={snap.text}
168+
onChange={(e) => {
169+
state.text = e.target.value
170+
}}
171+
/>
172+
)
173+
}
174+
```
175+
176+
`sync: true` disables batching so React re-renders within the same event loop tick, skipping the DOM update and preserving the caret position.
177+
151178
## Issue with `array` `proxy`
152179

153180
The following use case can occur unexpected results on `arr` subscription:

0 commit comments

Comments
 (0)