Mark As Completed Discussion

In React, the useRef hook is used to interact with DOM elements and store mutable values that persist across component renders.

Refs provide a way to access and manipulate the underlying DOM elements directly. They are especially useful when working with forms, managing focus, or triggering imperative animations.

To use the useRef hook, you first need to import it from the react library:

JAVASCRIPT
1import React, { useRef } from 'react';

Next, you can create a ref variable using the useRef hook:

JAVASCRIPT
1const myRef = useRef();

You can then attach the ref to a specific DOM element by passing it as a ref prop:

SNIPPET
1<input ref={myRef} type="text" />

Now, you can use the current property of the ref to access the DOM element:

JAVASCRIPT
1myRef.current.focus();

The useRef hook also allows you to store other mutable values, such as previous state values, without triggering a rerender. These values can be accessed and updated using the current property.

Here's an example that demonstrates the use of the useRef hook to manage focus in a form input field:

SNIPPET
1import React, { useRef } from 'react';
2
3function MyForm() {
4  const inputRef = useRef();
5
6  const handleSubmit = (e) => {
7    e.preventDefault();
8    console.log(inputRef.current.value);
9  }
10
11  return (
12    <form onSubmit={handleSubmit}>
13      <input ref={inputRef} type="text" />
14      <button type="submit">Submit</button>
15    </form>
16  );
17}

In this example, we create a ref variable inputRef using the useRef hook. We attach this ref to the input field using the ref prop. When the form is submitted, the value of the input field is logged to the console using inputRef.current.value.

The useRef hook is a powerful tool when you need to interact with DOM elements or store mutable values that persist across component renders. It can be used for various purposes, such as managing focus, accessing form values, and more.