Search code examples
javascriptreactjsreact-hooksuse-state

Is there a way to abstract multiple useState expressions into a separate file?


Supposing I have a React component with a large number of form inputs. Each of those inputs needs to map to state such that that information can be then used to create a large payload.

Is there a way to take something like the following:

const [formFieldExample1, setFormFieldExample1] = useState();
const [formFieldExample2, setFormFieldExample2] = useState();
// etc

... and condense it into a single expression?


Solution

  • How about using an object as state?

    const [fields, setFields] = useState({});  
    

    Then in your change handler

    const changeHandler = (event) =>{  
       setFields(previous => {  
           return {...previous, [event.target.name]: event.target.value})  
       }  
    }