Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Why should I use onChange?

Hey guys, I don't understand why should I use onChange event on input fields in React. Why not just to get an input value on submit clicked???

I think that performance is much slower, because event triggered every time user types.

2 Answers

Performance isn't really affected, or at least, not so you'd notice. Technically regular HTML inputs will maintain their own state for their value property/attribute, and there would already be onchange/keypress, etc events firing on them all the time.

The main reason you would use the onChange event handler in React is so that you can actually manage the state that is rendered as the input's value at all times, and do whatever you want with it (like display the input's value in another element/component, for example, a live preview).

If you only want the value to submit with other form data, then yes, you can achieve that without handling the onChange event. You would need to get a reference to the DOM node. See Refs to Components in the React docs.

Daan Schouten
Daan Schouten
14,454 Points

I am not sure which challenge you are referring to exactly, but generally speaking onChange is simply broader. If you were to only 'listen' to for example 'click', there might be another way that the value changes without a 'click'. You might still want to have the event triggered if the value changes, regardless of what causes it to change.

Hope this helps, Daan