How to Use useRef in React: Simple Guide and Examples
In React,
useRef creates a mutable object that persists across renders and can hold a reference to a DOM element or any value. You use it by calling const ref = useRef(initialValue) and attaching ref to a JSX element or accessing ref.current to read or update the value without causing re-renders.Syntax
The useRef hook returns a mutable object with a current property. You create it by calling const ref = useRef(initialValue). You can then attach ref to a JSX element to get its DOM node or use ref.current to store any mutable value.
- useRef(initialValue): Creates a ref object with
currentset toinitialValue. - ref.current: The mutable value or DOM node stored in the ref.
- Attaching ref to JSX: Use
ref={ref}on an element to access its DOM node.
javascript
const ref = useRef(null); // Attach to JSX element <input ref={ref} /> // Access or update value console.log(ref.current);
Example
This example shows how to use useRef to focus an input field when a button is clicked. The ref holds the input DOM node, and calling ref.current.focus() sets the cursor inside the input.
javascript
import React, { useRef } from 'react'; function FocusInput() { const inputRef = useRef(null); const handleFocus = () => { if (inputRef.current) { inputRef.current.focus(); } }; return ( <div> <input ref={inputRef} type="text" placeholder="Click button to focus" /> <button onClick={handleFocus}>Focus Input</button> </div> ); } export default FocusInput;
Output
An input box and a button labeled 'Focus Input'. Clicking the button puts the cursor inside the input box.
Common Pitfalls
- Not using
ref.current: The actual value or DOM node is insidecurrent, not the ref object itself. - Expecting ref changes to trigger re-render: Updating
ref.currentdoes not cause the component to re-render. - Using
useReffor state: For values that affect rendering, useuseStateinstead. - Forgetting to check if
ref.currentis null: The ref may be null before the element mounts.
javascript
import React, { useRef } from 'react'; function WrongRefUsage() { const countRef = useRef(0); // Wrong: This won't update the UI const incrementWrong = () => { countRef.current += 1; console.log('Count:', countRef.current); }; return ( <div> <p>Count (won't update): {countRef.current}</p> <button onClick={incrementWrong}>Increment</button> </div> ); } export default WrongRefUsage;
Output
A paragraph showing 'Count (won't update): 0' and a button. Clicking the button logs incremented count but UI does not change.
Quick Reference
| Concept | Description | Example |
|---|---|---|
| Create ref | Make a ref object with initial value | const ref = useRef(null); |
| Attach to element | Get DOM node reference | |
| Access value | Read or update the current value | ref.current |
| Use for DOM | Focus or measure elements | ref.current.focus() |
| Use for mutable value | Store value without re-render | ref.current = newValue |
Key Takeaways
useRef creates a persistent mutable object with a current property.
Attach ref to JSX elements to access DOM nodes directly.
Updating ref.current does not cause component re-renders.
Use useRef for mutable values that don’t affect rendering.
Always check if ref.current is not null before using it.