React useRef Hook
In this blog, we will explore the useRef
hook, understand its usage in applications, and create some real-world examples. The useRef
hook in React allows persisting values between component renders without triggering a re-render. Unlike the useState hook, which re-renders the component when its state changes, useRef
is not tied to the rendering cycle.
useRef
hook returns a mutable ref object, allowing you to store and access values across renders. It is particularly useful when accessing or modifying DOM elements directly.
1. Accessing Input Field Value
Let’s say we have a form with an input field, and we want to capture the value entered by the user when a button is clicked. Here’s how we can achieve it using the useRef
hook:
import React, { useRef } from "react";
export default function Form() {
const inputRef = useRef(null);
const handleClick = () => {
const value = inputRef.current.value;
alert(`Entered value: ${value}`);
};
return (
<div>
<input ref={inputRef} type="text" />
<button onClick={handleClick}>Submit</button>
</div>
);
}
In this example, we create a ref using useRef
and assign it to the input element using the ref
attribute. When the button is clicked, the handleClick
function is invoked. We access the input value using inputRef.current.value
and display it in an alert box.
Similar Posts:
2. Managing Focus on Input Field
Another common use case for the useRef
hook is managing focus on input fields. Let’s consider a scenario where we want to automatically focus on an input field when a component renders.
import React, { useEffect, useRef } from "react";
export default function AutoFocusInput() {
const inputRef = useRef(null);
useEffect(() => {
inputRef.current.focus();
}, []);
return <input ref={inputRef} type="text" />;
}
In this example, we use the useEffect hook in combination with useRef
to focus on the input field when the component mounts. The effect is triggered only once (due to the empty dependency array), ensuring that the focus is set only on the initial render.
3. Creating a Mutable Variable
The useRef
hook can also be used to store mutable values that persist across renders. These values are not directly tied to the component’s state, making them useful for scenarios where a value needs to be preserved between renders but doesn’t trigger re-renders.
import React, { useRef } from "react";
export default function Counter() {
const countRef = useRef(0);
const handleIncrement = () => {
countRef.current += 1;
console.log(`Count: ${countRef.current}`);
};
return (
<div>
<button onClick={handleIncrement}>Increment</button>
</div>
);
}
In this example, we initialize a mutable value using useRef
and increment it on each button click. The updated value is accessed using countRef.current
. Since the value is not part of the component’s state, it doesn’t trigger a re-render.
Summary
The useRef
hook in React is a powerful tool for interacting with DOM elements, managing focus, and storing mutable values between renders. Its ability to persist data without triggering re-renders makes it a valuable addition to a developer’s toolkit. By leveraging the useRef
hook, you can unlock new possibilities for building dynamic and interactive user interfaces in React.