Reset input field values tracked by useRef in React


Borislav Hadzhiev

Last updated: Apr 16, 2022


Check out my new book

Reset input field values tracked by useRef in React #

To reset input field values tracked by useRef in React:

  1. Set the ref's value property to an empty string, e.g. ref.current.value = ''.
  2. If dealing with multiple uncontrolled fields in a form, use the form's reset() method.

reset useref input value

import {useRef} from 'react'; const App = () => { const ref = useRef(null); const handleClick = () => { // 👇️ reset input field's value ref.current.value = ''; }; return ( <div> <input ref={ref} id="message" name="message" type="text" /> <button onClick={handleClick}>Clear field</button> </div> ); };

The code sample resets the value of the input field when the button is clicked.

The useRef() hook can be passed an initial value as an argument. The hook returns a mutable ref object whose .current property is initialized to the passed argument.

Notice that we have to access the current property on the ref object to get access to the input element on which we set the ref prop.

When we pass a ref prop to an element, e.g. <input ref={myRef} />, React sets the .current property of the ref object to the corresponding DOM node.

This approach can be used to clear the value of as many uncontrolled input fields as necessary.

Alternatively, when working with uncontrolled input fields, you can also use the reset() method to clear the values of all input fields in the form.
import {useRef} from 'react'; const App = () => { const firstRef = useRef(null); const lastRef = useRef(null); const handleSubmit = event => { console.log('handleSubmit ran'); event.preventDefault(); // 👇️ clear all input values in the form; }; return ( <div> <form onSubmit={handleSubmit}> <input ref={firstRef} id="first_name" name="first_name" type="text" /> <input ref={lastRef} id="last_name" name="last_name" type="text" /> <button type="submit">Submit form</button> </form> </div> ); }; export default App;

useref reset multiple fields

We used the event.preventDefault() method in the handleSubmit function to prevent the page from refreshing when the form is submitted.

The reset() method restores a form element's default values.

Regardless of how many uncontrolled input fields your form has, a single call to the reset() method clears all of them.

This approach wouldn't be necessary if you only have a single uncontrolled input field that is not wrapped in a form element. In that case, I'd simply set the value property on the ref to an empty string, e.g. ref.current.value = ''.

However, if you have a form with multiple uncontrolled fields, you can reset all of their values with a single call to the form's reset() method.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.