skip to Main Content

I have a form in React with several controlled inputs.

I always read and had the impression that separately changing states should be stored separately:

For example:

const [text1, setText1] = useState();
const [text2, setText2] = useState();
const [text3, setText3] = useState();

However, now, because of a specific way of validation, I need to combine all form data in one object, and it should run on every state change (value change).

How should I approach this? Is this article a good guide? Is this best practice and efficient? I’m also afraid of lots of "wasted" data and sloppy performance since useState creates immutable objects.

2

Answers


  1. I suggest you try Formik, it has a great documentation and quite easy to use. Also, input values automatically come as an object like:

        values = {
          text1: 'text1', 
          text2: 'text2', 
          text3: 'text3'
        }
    
    Login or Signup to reply.
  2. It’s not that all states need to be separated into individual hooks (you could certainly break all your state down this way if you really wanted to) nor do you want only a single state object with everything in it, but a general rule is that related values are commonly grouped together into states, while unrelated values are individualized.

    Example of related values is your form data. A form is a collection of "inputs" that are often updated together (user needs to fill in the form), and validated and submitted as a group.

    Examples of unrelated values might be independent toggles, or separate fetched API data. These are all independently referenced, consumed, and updated and should each be their own declared state.

    Basically you want to avoid the extremes:

    • One single state object with everything in it. You’d need to copy forward all the unrelated state that isn’t being updated for each state update.
    • A state for each and every value that may be updated. You’d use several "setStateX" to update values that often update together.

    Both cases can affect readability/maintainability, and can make the code less DRY.

    How you decide what values are related is where it gets subjective and is really up to you and your projects’ needs.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search