Skip to main content

useRef

The useRef hook in React is used to access and interact with a DOM element or to keep a mutable reference to a value that doesn't trigger a re-render when it changes. Unlike state variables, changes to a ref do not cause the component to re-render. This makes useRef useful for various scenarios, such as focusing on input fields, measuring DOM elements, or keeping track of previous props/state.

Basic Syntax

The basic syntax of useRef is as follows:

const myRef = useRef(initialValue);

Here, initialValue is the initial value you want to assign to the ref. It's optional and defaults to null.

How it Works

  1. Initialize Ref: You initialize a ref using useRef() and assign it to a variable.

    const inputRef = useRef(null);
  2. Attach Ref to Element: You attach the ref to a React element using the ref attribute.

    <input ref={inputRef} />
  3. Access Ref: You can now access the ref in your component logic.

    const handleFocus = () => {
    inputRef.current.focus();
    };

Example

Here's a simple example to demonstrate how useRef can be used to focus an input field:

import React, { useRef } from 'react';

function App() {
const inputRef = useRef(null);

const handleFocus = () => {
inputRef.current.focus();
};

return (
<div>
<input ref={inputRef} type="text" />
<button onClick={handleFocus}>Focus Input</button>
</div>
);
}

export default App;

In this example, clicking the "Focus Input" button will focus the input field. This is done by calling the focus() method on the current property of inputRef.

Use Cases

  • Focus Management: As shown in the example, you can use useRef to programmatically set the focus on form elements.

  • Measurements: You can use it to measure the dimensions of a DOM element.

  • Previous Values: You can use it to keep track of previous values of props or state without causing re-renders.

  • Integration with Third-Party Libraries: Sometimes you may need to integrate with a third-party library that requires direct access to a DOM node. useRef can be useful in such scenarios.

Caveats

  • The current property of the ref object is mutable and can be changed freely. However, changing it does not trigger a re-render.

  • If you pass a ref object to a function component, you can't access its instance, as function components don't have instances. You can only use it for DOM access in such cases.

Summary

The useRef hook provides a way to access DOM nodes or keep a mutable reference to a value. It's a versatile hook that comes in handy for various tasks that don't require triggering a re-render.

info

Below code block in index.js would intentinally triggers useState, useMemo and useReducer and may be some other effects twice

/src/index.js
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);