Search code examples
reactjsuse-state

Why we need to use onChange event in react js for the input fields


I have a question that why we need to use onchange event in react and set the state on every change event and why we cannot change the state of all the input fields of the form on submit button? When we use onChange in an input field, it performs all the inbetween steps to set the state on every change event, so why don't we use event.target to store all the states on submit or it is not possible?


Solution

  • you can control the form with state and then you will need to change the state whenever user changes the input by handling onChange method and updating the state, because the input always shows the state value and not whatever user types.

    if you want to reset your input fields after submit without using state you have to get the refs of your input (by using useRef or createRef) and change the value property of input imperative after submission.