Handling inputs before mount when using SSR #2030
Replies: 2 comments
|
Disabling the inputs until mount is also possibly an option, as I think my current setup doesn't have any progressive enhancement for non js environments, but also feels like a hack. |
|
What you're describing is the standard SSR hydration race for any controlled input, not something specific to how this form library reads values, so it's worth treating as a general hydration problem rather than looking for a form-level fix. The sequence: the server renders the input with its initial value baked into the HTML. The browser paints that HTML immediately, before React (or whichever framework) has attached any event handlers, that's the whole point of SSR. If the user types during that window, the DOM node's value changes, but the framework's internal state (what it thinks the value is) hasn't been touched, since no handler ran yet. Once hydration completes and the user blurs the field, the framework re-renders the input from its own state and overwrites whatever's actually sitting in the DOM. Your keystrokes just get discarded because the framework never knew they happened. Disabling the input until mount isn't a hack, it's the standard mitigation for exactly this race. Frameworks that ship SSR plus interactive forms generally recommend disabling or otherwise blocking interaction with controlled inputs during the hydration window for this reason: const [mounted, setMounted] = useState(false)
useEffect(() => setMounted(true), [])
<input disabled={!mounted} ... />The alternative some libraries use is rendering the input uncontrolled ( |
Uh oh!
There was an error while loading. Please reload this page.
When using SSR the form is displayed immediately, but any input a user makes before the form is properly hydrated are overwritten when the input is blurred. Right now this is happening about 30% of the time in my tests.
Is there any way for the form component to pull an existing value off any inputs using refs or something on mount? Adding a few ms of sleep in my test might help with this but it's kind of annoying and probably could impact users with slow internet connections too.
video.webm
All reactions