Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
useRef() | Functional Components and Hooks
React Tutorial
course content

Course Content

React Tutorial

React Tutorial

1. Getting Started
2. Lifecycle Methods
3. Functional Components and Hooks
4. Advanced Topics

book
useRef()

useRef is a hook in React that allows you to create a mutable reference to a value. It is a way to store a value that will not trigger a re-render when it changes.

Here's an example of how to use useRef:

In this example, the inputRef value is created using useRef and passed as the ref attribute to the input element. The focusInput function uses the current property of the inputRef to focus the input. Because the inputRef value is mutable, it can be updated without causing a re-render.

You can also use useRef to store mutable values other than DOM elements. For example, you might use it to store a timer ID or a WebSocket connection.

The value stored in the ref is mutable, but the reference itself is not. This means that if you update the value of the ref, it will not cause a re-render.

For example:

In this example, the countRef value is created using useRef and initialized to 0. The increment function increments the current property of the countRef, but this does not cause a re-render.

There are a few nuances to be aware of when using useRef:

  • The value stored in the ref is mutable, but the reference itself is not. This means that if you update the value of the ref, it will not cause a re-render.

  • The value of the ref will not change between renders, so it can be used as a way to preserve state across renders.

  • If you need to store a value that should trigger a re-render when it changes, consider using the useState hook instead.

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 3. Chapter 6
We're sorry to hear that something went wrong. What happened?
some-alt