How useRef Hook is useful in React ?
Last Updated :
24 Jul, 2024
Hooks provides a way to useState and other React features in functional components without the need for class components. We can either use built-in hooks or customize and make our own. One of those hooks in useRef. It allows reference to a value that does not require rendering. It can be used to store a mutable value that does not cause a re-render when updated. It can be used to access a DOM element directly.
Primary Uses of useRef:
1. Accessing DOM elements
Referring to DOM elements directly within your component is a common use case for useRef. Instead of employing DOM queries like document.getElementById, useRef allows direct referencing of elements.
JavaScript
import React, { useRef } from 'react';
const CustomComponent = () => {
const inputRef = useRef(null);
const handleClick = () => {
// Focus the input element on button click
inputRef.current.focus();
};
return (
<div>
<input ref={inputRef} type="text" />
<button
onClick={handleClick}>
Focus Input
</button>
</div>
);
};
2. Storing previous values
Utilizing useRef enables the storage of a value that persists across renders without triggering re-rendering when updated. This proves beneficial for maintaining previous values without causing unnecessary renders.
JavaScript
import React, {
useEffect,
useRef
} from 'react';
const CustomValueComponent = ({ value }) => {
const prevValueRef = useRef();
useEffect(() => {
prevValueRef.current = value;
}, [value]);
return (
<div>
<p>Current Value: {value}</p>
<p>Previous Value: {prevValueRef.current}</p>
</div>
);
};
3. Navigating External Libraries
In certain scenarios, when incorporating external libraries that require a mutable reference to data, useRef can prove to be quite useful. Keep in mind that as useRef doesn't induce re-renders, if you require component updates to be reflected in the UI, useState should be preferred. Reserve the use of useRef for managing mutable values or references without influencing component rendering.
JavaScript
import React, {
useEffect,
useRef
} from 'react';
import externalLibrary from 'some-external-library';
const CustomLibraryComponent = () => {
const dataRef = useRef([]);
useEffect(() => {
// Update the external library with the latest data
externalLibrary.updateData(dataRef.current);
}, []);
//...
};
Combining useRef, useImperativeHandle, and forwardRef enables the creation of custom input components with programmatically focused input methods. This approach offers a controlled and explicit means of interacting with a child component's methods or properties from its parent.
JavaScript
import React, {
useRef,
useImperativeHandle,
forwardRef
} from 'react';
const ModifiedInputComponent = forwardRef((props, ref) => {
const inputRef = useRef(null);
// Expose the 'focusInput' method to the parent component
useImperativeHandle(ref, () => ({
focusInput: () => {
inputRef.current.focus();
}
}));
return (
<input
ref={inputRef}
type="text"
placeholder={props.placeholder}
/>
);
});
export default ModifiedInputComponent;
Creating a reference to the input element in the child component is achieved using useRef. Subsequently, by utilizing useImperativeHandle, we expose a method named focusInput to the parent component via the ref. This mechanism empowers the parent component to invoke focusInput on the child component's ref, facilitating programmatic focusing of the input element.
JavaScript
import React, { useRef } from 'react';
import ModifiedInputComponent
from './ModifiedInputComponent';
const ModifiedParentComponent = () => {
const inputRef = useRef(null);
const handleFocusButtonClick = () => {
/*
Call the 'focusInput' method of
the child component
*/
if (inputRef.current) {
inputRef.current.focusInput();
}
};
return (
<div>
{/* Child component with the ref */}
<ModifiedInputComponent ref={inputRef}
placeholder="Enter your name" />
<button onClick={handleFocusButtonClick}>
Focus Input
</button>
</div>
);
};
export default ModifiedParentComponent;
Utilizing useRef in the parent component establishes a reference (inputRef) aimed at interacting with the focusInput method of the child component. Upon clicking the "Focus Input" button, the handleFocusButtonClick function executes. Within this function, the focusInput method is invoked on the child component's ref, consequently focusing the input element.
This example showcases the collaborative use of useRef and useImperativeHandle to construct a more regulated interface for parent components to interact with child components.
Steps to Create a React App:
Step 1: Create a React application using the following command.
npm create-react-app my-app
Step 2: Naviage to the root directory of your folder using the following commad.
cd my-app
Example: Below is an example to show a scnerario where useRef is useful.
JavaScript
import { useRef } from 'react';
export default function Counter() {
let ref = useRef(0);
function handleClick() {
ref.current = ref.current + 1;
alert('You clicked' +
ref.current + 'times');
}
return (
<button onClick={handleClick}>
Click me!
</button>
);
}
Start your application using the following command.
npm start
Ouput:
Conclusion:
Referring to DOM elements directly within React components is a common need, but traditional methods like document.getElementById() can be inefficient in a React context. useRef offers a more efficient way to reference DOM elements, manage mutable values, and interact with child components imperatively. Its ability to persist values across renders without triggering re-renders is particularly useful for scenarios like managing DOM focus efficiently. Thus, useRef serves as a valuable tool for optimizing performance and state management in React applications.
Similar Reads
How to Use useState() Hook in NextJS ?
In this article, we will learn How to use useState() hook provided by the 'react' library in the NextJS project. useState() HookThe React JS library includes the useState() hook. It is very useful in order to manage the state in our Next Js application. It allows us to add the state, and update the
3 min read
useRoutes Hook in React Router
React Router is a library that is used for handling navigation and routing in React applications. It provides a way to navigate between different components or pages while maintaining a single-page application (SPA) structure. One of the key features is the useRoutes hook. It allows you to define ro
4 min read
ReactJS useRef Hook
The useRef Hook is a built-in React Hook that returns a mutable reference object (ref) that persists across renders. Unlike state variables, updating a ref does not trigger a component re-render. Syntax const refContainer = useRef(initialValue);useRef returns an object { current: initialValue }.The
3 min read
Ref Hooks in React
Ref Hooks provide a way to access and interact with the DOM (Document Object Model) nodes directly within functional components. Before hooks, refs were primarily used in class components. However, with Ref Hooks, functional components can also take advantage of this capability, enhancing flexibilit
4 min read
Purpose of useReducer hook in React
The useReducer hook is a state management hook in React that provides an alternative to the useState hook. It is used when the state of a component is complex and requires more than one state variable. Syntax:const [state, dispatch] = useReducer(reducer, initialState, init)reducer: The reducer is a
3 min read
Resource Hooks in React
In React, components often need to access external resources such as data from promises or context information for styling. Managing these resources within the component state could lead to unnecessary complexity and performance overhead. React provides a simple solution with the 'use' hook to overc
3 min read
useLoaderData Hook in React Router
useLoaderData is a hook provided by React Router. React Router is a JavaScript framework that helps to create and handle routing in React applications. This hook helps to fetch the data for the component before it renders, this improves performance and prevents empty states. Data FetchingWithout the
3 min read
ReactJS useEffect Hook
The useEffect hook is one of the most commonly used hooks in ReactJS used to handle side effects in functional components. Before hooks, these kinds of tasks were only possible in class components through lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount. What is
5 min read
How to use useMemo Hook in a Functional Component in React ?
In React development, optimizing performance is crucial for delivering responsive and fast user experiences. One way to achieve this is by using the `useMemo` hook. In this article, we'll explore what `useMemo` is, why it's beneficial, and how to use it effectively in functional components. Table of
3 min read
React useState Hook
The useState hook is a function that allows you to add state to a functional component. It is an alternative to the useReducer hook that is preferred when we require the basic update. useState Hooks are used to add the state variables in the components. For using the useState hook we have to import
5 min read