The useRef Hook enables you to store values between renderings.

It can be used to hold a mutable value that does not require a re-render when changed.

It allows you to access a DOM element directly.


Does Not Cause Re-renders

If we tried to count how many times our application renders using the useState Hook, we’d get stuck in an infinite loop because the Hook itself causes a re-render.

To circumvent this, we can use the useRef Hook.

Example:

Use useRef to monitor application renderings.

----- Example mukava -----

UseRef() returns only one item. It returns an object named current.

When we initialize useRef, we set the starting value to useRef(0).

Consider this: const count = {current: 0}. We may get the count by using count.current.

Run this on your machine and try typing into the field to see if the application render count increases.

Accessing DOM Elements

In general, we want React to handle all DOM manipulations.

However, there are several situations where useRef can be used without generating problems.

In React, we may use the ref attribute to retrieve an element directly in the DOM.

Example

Use useRef to focus the input.

----- Example mukava -----

Tracking State Changes

The useRef Hook can also be used to save prior state values.

This is because we can keep useRef values between renderings.

Example

Use useRef to maintain track of past state values.

----- Example mukava -----

This time, we utilize a combination of useState, useEffect, and useRef to remember the prior state.

The useEffect updates the useRef current value every time the inputValue is changed by putting text into the input field.

Share this Doc

useRef

Or copy link

Explore Topic