The boring React Redux forms

Forms are hard. It’s the same as validation. No magic framework will save us from writing our app code. The wrong abstraction is the wrong abstraction no matter how hard you push the human limits.

UPDATE: I made beautiful forms without Redux. Check it 🐕✨.

Pokud vás zajímá více, pořádám školení: https://javascript-skoleni.cz

https://fee.org/articles/socialists-are-scarcity-deniers/
Some people, when confronted with a problem, think “I know, I’ll use some library.” Now they have two problems. Or more.
http://redux-form.com

Let’s start with a simple statement. You might not need Redux or redux-form for React forms. React component local state is often good enough. For beginners, it seems quite verbose that every form field should have an own handler. But it’s not verbose, it’s explicit. And we can refactor the code later. For example, we can leverage name attribute.

Should I put form state into Redux?

Go, read this nice article https://goshakkk.name/should-i-put-form-state-into-redux. I will wait… OK, now we know when we need Redux.

Redux forms

Are not easy, because programmers (me) often tend to overthink the code not even yet written. If you are like me, then stop thinking and just write the first code from your head. We can always refactor later. So, look what have I realized and wrote after several refactors:

  1. A form is a typed object. Types are highly addictive because they help us to reason about application model.

2. We need forms reducer for initial and changed states. Note one user form can have many changed states. That’s because app remembering not finished edits (imagine we can edit more users) has great UX. Facebook app does that 🎶. Twitter not 😂.

3. Can we have just one action for all that stuff? Yep. Isn’t weird we have to pass whole user form state to action? No. It’s actually great because we can set and change anything within out stateless functional form component without magic helpers. Also, immutable change checking is faster with several objects than hundreds of fields.

4. “Shut up and show me the reducer!” Here is it. Note little set helper for other forms, and reject(isNil) removing null values when we reset form.

5. And final piece 🏒🥅

And we are done. This is it. It’s fast, scalable, hackable, typed, zero abstraction, React Redux form. And it’s easy. Remember, bad abstraction is much worse than little repeating here and there. If you are curious about Heading, TextInput, etc. read about my universal CSS in JS approach.

Next time, I will show how to add universal validation, once I will port it from the previous Este 🍀