DEV Community

Discussion on: A Tip to Make Your React Code Better and Cleaner

Collapse
 
muni profile image
Muni Perez

Hey Christian,

Good point about code-reusability. However, in my opinion, this is not a good approach. First, forms are unique and although you see a pattern of inputs, each input is very unique, with validation, different types of inputs, etc. Then eventually you will see yourself writing conditions and props for all the different scenarios that a form can have and then the props will get really complex and your component will be completely unusable and unmaintainable, and you will break it up in smaller pieces and be back at the original "issue" of writing a lot of components.

I would suggest you to look at form libraries like Formik (jaredpalmer.com/formik/) which offers reusability in the form logic but gives you the flexibility to render the UI elements as you wish.

Collapse
 
canopix profile image
Canopix

I second this, also I suggest looking react-hook-forms that make the same thing

Collapse
 
christiankastner profile image
Christian

Ahh Gotcha. I was going for more of an illustrative example to try to abstract away implementation details but didn't consider the fact of form validation. Thanks fellas!

Thread Thread
 
muni profile image
Muni Perez

Sure.

Also, I would like to add that having a big number of components is not bad. If you need to have many components, you will have them and that's just fine. What is bad is having unnecessary components. However, having fewer components can also be bad.

Instead of attaching to the number of components, you can think about one of the main principles of component philosophy. Is it breaking the single responsibility principle? Then it's time to break it up in smaller pieces. That's the basic thing and you can't go wrong with that ;) Large scale enterprise applications will have thousands of components.

Making it "inconvenient" for adding new components, in my opinion, is not beneficial for scalability. Create just the components that you need, not more, not less.

Collapse
 
amirulabu profile image
Amirul Abu

I have experience first hand where generalizing a form component is a bad thing. especially if you are working against a spec or design. Each form have their own behaviour and logic that ends up making a mess in the general form component.