useRef
Pritpal Singh
Posted on September 12, 2024
What is useRef
?
The useRef
hook in React is used to access and interact with DOM elements directly or to keep a mutable value that does not cause re-renders when changed. It provides a way to persist values across renders without triggering a component update.
How useRef
Works
useRef
returns a mutable object called a "ref object" with a .current
property. This property can hold a value that persists across re-renders.
Basic Syntax
const myRef = useRef(initialValue);
-
initialValue
: The initial value for the ref object. This is optional.
Example 1: Accessing DOM Elements
In this example, we'll use useRef
to access a DOM element directly.
- Create the Component
import React, { useRef, useEffect } from 'react';
const FocusInput = () => {
// Create a ref with useRef
const inputRef = useRef(null);
useEffect(() => {
// Focus the input field when the component mounts
inputRef.current.focus();
}, []);
return (
<div>
<input ref={inputRef} type="text" placeholder="Focus me on mount" />
</div>
);
};
export default FocusInput;
Explanation:
-
useRef(null)
creates a ref object. -
inputRef.current
gives access to the input element. -
useEffect
is used to focus the input field when the component mounts.
Example 2: Keeping Mutable Values
In this example, we'll use useRef
to keep a mutable value that does not cause re-renders when updated.
- Create the Component
import React, { useRef, useState } from 'react';
const Timer = () => {
const [count, setCount] = useState(0);
const timerRef = useRef(null);
const startTimer = () => {
if (timerRef.current) {
clearInterval(timerRef.current);
}
timerRef.current = setInterval(() => {
setCount(prevCount => prevCount + 1);
}, 1000);
};
const stopTimer = () => {
if (timerRef.current) {
clearInterval(timerRef.current);
}
};
return (
<div>
<h1>Time: {count}s</h1>
<button onClick={startTimer}>Start Timer</button>
<button onClick={stopTimer}>Stop Timer</button>
</div>
);
};
export default Timer;
Explanation:
-
timerRef.current
is used to store the timer ID. -
startTimer
andstopTimer
functions usetimerRef.current
to manage the timer. - Updating
timerRef.current
does not cause a re-render of the component.
Summary
-
useRef
creates a mutable ref object with a.current
property. - Use
useRef
to access DOM elements directly. - Use
useRef
to keep mutable values that do not cause re-renders.
That’s it! useRef
is a powerful and versatile hook that’s useful in many scenarios.
Posted on September 12, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 29, 2024