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

Зміст курсу

React Tutorial

React Tutorial

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

bookuseRef()

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.

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 3. Розділ 6
some-alt