Previous Lesson Home Page Hooks Next Lesson

Lesson 7

The useState hook

Registration form with a single state value - useState hook 

Note that when we use objects for state with the useState React hook, we have to perform the merge manually by spreading in the entire object because each time you call the method setForm in the example below, it replaces the whole object form with new object form. If you do not merge manually, the result of the last input field will be retained and the result of the other two input fields will be lost. 

In cases, where all the properties of an object are updated automatically, such as in case of mouse movement on screen having x and y coordinates, no manual merge is needed as all the properties are assigned values anew each time you call the method setMousePosition() to update the object that represents both the x and y coordinates of the position of the mouse. setMousePosition({x: event.pageX, y: event.pageY}). On the other hand, in the example below, each time we call the method onChange={handleChange} in each input, the handleChange calls setter method setForm() which sets the whole object form. Thus, manually spreading the value is must in this case in order to retain the values of the input fields previously filled by the user.

I f you do not use an object for state, and handle each input field individually, then you don't need to create a generic function as we do (setForm) in the example below. You can just write an inline function and use the setters on each field directly as we did in the previous lesson in which we created a log in form. onChange={setUsername(event.target.value)}

For related pieces of state, like in the example on log in form in the previous lesson, use multiple state values only when there are just a couple of things to manage. In cases, where you have more than a couple of fields, like in the example above, then it makes sense to group them together within a single object and create a general handle function (e.g., handleSubmit in the example above). You can then call this general handle in the onChange of each field but don't forget to manually spread the entire object when performing an update for any of the input values. 

Previous Lesson Home Page Hooks Next Lesson
© Copyright 2020 – Ajmal Khan