If you're just diving into React and you’ve heard about useRef
but have no idea what it’s for—don’t worry, you’re not alone. Most beginners focus on useState
or useEffect
first, which makes total sense. But today, we're going to explore a lesser-known but super useful hook: useRef.
What is useRef?
Think of useRef
like a magic box that you can put any value into—and React won’t complain when you change it. It’s perfect for keeping a reference to something that doesn’t need to trigger a re-render. That "something" is often a DOM element, but not always.
Basic Syntax
import { useRef } from 'react';
function MyComponent() {
const myRef = useRef(null);
return <div ref={myRef}>Hello!</div>;
}
Here, myRef
is like a pointer to the div element. You can now do things like myRef.current.focus()
if it were an input, for example.
useRef vs useState
- useState: Changing the value causes the component to re-render.
- useRef: Changing the value does not trigger a re-render.
This makes useRef
great for keeping things like timers, counters, or previous props without causing a bunch of unnecessary updates.
Example: Focusing an Input Field
import { useRef } from 'react';
function FocusInput() {
const inputRef = useRef();
const handleClick = () => {
inputRef.current.focus();
};
return (
<>
<input ref={inputRef} type="text" />
<button onClick={handleClick}>Focus Input</button>
</>
);
}
This is one of the most common use cases—focusing an input without needing to use state or wait for a re-render.
Another Use Case: Keeping Previous Values
You can also use useRef
to store previous props or state values:
import { useEffect, useRef, useState } from 'react';
function PreviousValueTracker() {
const [count, setCount] = useState(0);
const prevCountRef = useRef();
useEffect(() => {
prevCountRef.current = count;
});
const prevCount = prevCountRef.current;
return (
<>
<p>Current: {count}</p>
<p>Previous: {prevCount}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</>
);
}
Every time the count changes, the previous count gets stored in the ref. And since useRef
doesn’t cause a re-render, it’s perfect for this kind of "history keeping."
When Not to Use useRef
- If you want to track something and re-render when it changes—useState is better.
- If you’re trying to run code when something updates—use useEffect.
- useRef is for when you need to store something persistently across renders without triggering updates.
Real-Life Examples
1. Debouncing user input: Store a timeout reference.
2. Video/audio controls: Access play/pause methods from the DOM directly.
3. Keeping track of mounted state: To avoid setting state on unmounted components (common in async calls).
useRef
is your secret weapon when working with DOM elements directly or storing mutable values between renders without causing updates. It's easy to overlook but super handy once you know when and why to use it.
Tip: If you're just starting with React, master
useState
anduseEffect
first. Then, adduseRef
to your toolbox—it’ll come in handy more often than you think!
0 Comments:
Post a Comment