My controlled input dilemma with react & redux


“An input that does not supply a value (or sets it to null) is an uncontrolled component. In a controlled input, the value of the rendered element will always reflect the value prop.”

The input onChange event is something I always been careful with. You do not want to execute too much code while a user is completing a form, it’s already an unpleasant experience in the first place without having sluggish inputs. That is why I am having a bit of an issue being told that I should handle all inputs state at all time.

The goal of controlled inputs is predictability and reliability™. While react setState approach is generally fine performance wise, with redux it’s another story. Passing down actions, executing middlewares, to finally get to the reducers at every keystroke is expensive.

I get the why, but I don’t think web forms were built to be used that way & this add a level of complexity I am not always happy with. I am also not surprised redux-form have “>performance issues with long form right now.

So what if we keep them uncontrolled?

With an uncontrolled input you have 2 things you want to handle, default values & validation.

Fortunately react provide you with a defaultValue property. Like its name is saying, this will only render once. You won’t be able to change the props on subsequent renders.

That can be an issue for certain forms & functionalities. Suggestion Boxes, select all checkboxes, all those types of inputs, you will need to keep the state in sync. This is fair, this is advanced form functionalities.

Uncontrolled input validation

Form validation is not a new theme for me, and for some reasons I am always draw back to that subject. Don’t get me wrong, redux-form is an awesome bit of code. It’s just a tiny bit too big for me and I am not confortoble handling all my forms to it.

My forms states are mine, controlled or uncontrolled is not a concern of my input validation state, it’s about validating the value. I want my validation middleware to keep my form validation state, that’s it.

That is why I built redux-form-validator. A small validation middleware that validate inputs. My goal was:

* Fast integration
* Fast validation
* Keep out of my way
* Small enough that I can easily adapt it in the future

Source code | Demo

Should you do uncontrolled inputs? I don’t know, but if you feel like controlled inputs is a drag now you have a validation alternative.

Controlled inputs with redux

If you still want to keep all your inputs controlled, I would look at using the setState approach on the onChange event and restrain yourself of pushing events down the redux flow on each keystroke.

That way you will be sure to keep a good user experience, even with long forms.

Ressources

Redux github issue discussion on uncontrolled input
React docs on form
Controlled vs Uncontrolled Components in React


Source link