Search code examples
reactjsformsreact-hooks

How to store form data correctly in React?


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.


Solution

  • 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.