Full Stack Developer interested in making lives better through software
Updated Aug 13, 2019
While working with react it is almost inevitable to come across controlled components.
While working with react it is almost inevitable to come across controlled components. A controlled component is a react component that controls the values of input elements in a form using setState().
Before the new hooks API was introduced, you could only use class components for this purpose since they are the only ones that can store state and have access to the setState API. But now with the introduction of hooks, we can finally handle state changes in any component (functional or class) greatly simplifying writing controlled components.
At first, it may seem there is nothing wrong with it, but what would happen if instead of two input fields we had 5 or 10? we will need 10 handleSomeInputFieldChange function handlers. THIS APPROACH IS NOT SCALABLE
Let’s rewrite our component to control the input fields using hooks:
The first change to notice is that our component is now a function, with the introduction of the useState hook we are no longer obligated to convert our functional components into class components when we want to use local state.
Secondly, we are now programmatically setting values to our state variables, the way we accomplished this is by adding a new name attribute to the input fields in lines 17 and 25. The magic happens in line 8: [e.currentTarget.name]: e.currentTarget.value here we are using that name as the property value for our state object and assigning the input value to it.
This approach is scalable since it doesn’t matter the number of input fields in this form, they will all use the same handleInputChange and the local state will be updated accordingly. Beautiful!
Now! let’s make this even better by abstracting the hook into its own file to make it reusable.
Isn’t it cool? all the setState and input handlers boilerplate have been completely removed from our component. with our new hook creating controlled components is simple as it gets, making our component more readable and focusing on the specific business logic that it was created for.
Just like HOCs and render prop, hooks allow us to reuse logic in our components. We can leverage this to do all sort of abstractions.