useState — Complete Guide
useState — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of React.js Tutorial on Toolliyo Academy.
On this page
React.js Tutorial · Lesson 23 of 100
useRef
Beginner ✓ → Intermediate → Advanced → Professional
Intermediate · 2 — Building apps · ~14 min read · Module 3: Hooks & Component Design
Introduction
You know the basics now. Here we use useRef in real app situations — forms, pages, and data. Still plain language, just a bit more depth. useRef holds a mutable value that persists across renders without causing update the screens when it changes. Common uses: DOM references and storing previous values. Sometimes you need to focus an input, measure an element, or keep a timer id — without triggering a UI update.
Hooks look strange at first. Every React developer felt that way. Use the same pattern from this lesson again and again until it feels normal.
When will you use this?
Reach for hooks whenever the screen must react to user input, time, or data from an API.
- Hooks power live search, dark mode toggles, and fetching data when a page opens.
- Almost every React job posting mentions hooks — this is core daily work.
Real-world: HDFC OTP auto-focus
After SMS OTP is sent, first digit box should focus automatically. useRef points to the input without re-rendering the whole login form.
Production-style code
function OtpInput({ length = 6, onComplete }) {
const firstRef = useRef(null);
useEffect(() => {
firstRef.current?.focus();
}, []);
const [digits, setDigits] = useState(Array(length).fill(''));
function handleChange(i, value) {
const next = [...digits];
next[i] = value.slice(-1);
setDigits(next);
if (next.every(Boolean)) onComplete(next.join(''));
}
return (
<div className="otp-row">
{digits.map((d, i) => (
<input
key={i}
ref={i === 0 ? firstRef : null}
value={d}
onChange={e => handleChange(i, e.target.value)}
maxLength={1}
/>
))}
</div>
);
}
What happens in production: Better UX on mobile banking — users start typing OTP immediately; ref access does not trigger extra renders.
Lesson example (start here)
Copy this smaller example first. Once it works, compare it with the real-world code above.
import { useRef } from 'react';
function SearchBox() {
const inputRef = useRef(null);
function focusInput() {
inputRef.current.focus();
}
return (
<>
<input ref={inputRef} type="search" />
<button onClick={focusInput}>Focus</button>
</>
);
}
Line-by-line walkthrough
| Code | What it means |
|---|---|
import { useRef } from 'react'; | Imports code from React or another file so you can use it here. |
function SearchBox() { | Defines a function — often a component or event handler. |
const inputRef = useRef(null); | Part of the useRef example — read it together with the lines before and after. |
function focusInput() { | Defines a function — often a component or event handler. |
inputRef.current.focus(); | Part of the useRef example — read it together with the lines before and after. |
} | Closes a block started by { or ( above. |
return ( | Sends UI or a value back to whoever called this function. |
<> | Part of the useRef example — read it together with the lines before and after. |
<input ref={inputRef} type="search" /> | JSX tag — a UI element or custom component on the page. |
<button onClick={focusInput}>Focus</button> | JSX tag — a UI element or custom component on the page. |
</> | Part of the useRef example — read it together with the lines before and after. |
); | Closes a block started by { or ( above. |
} | Closes a block started by { or ( above. |
How it works (big picture)
- ref={inputRef} attaches the DOM node to inputRef.current.
- Changing .current does not update the screen the component.
Do this on your computer
- Create a ref and attach to an input.
- Call .focus() from a button click.
- Try storing interval id in a ref for cleanup.
- Read the real-world section and name which part of the app uses this topic.
- Run the example locally and confirm the same behavior in the browser.
- Change one value in the example (text, initial state, or URL) and predict what will happen before you save.
Experiments — try changing this
- Change text or labels in the example and save — watch the browser update.
- Break the code on purpose (remove a bracket), read the error message, then fix it.
- Open React DevTools (browser extension) while running useRef and inspect component props/state.
Remember
useRef persists values without update the screen. Great for DOM access and instance variables. ref={myRef} on JSX elements.
Common questions
useRef vs useState?
useState triggers re-render on change; useRef does not.
How long should I spend on useRef?
Until you can explain it in your own words and run the example without looking at the answer. Beginners often need 30–60 minutes per new hook or routing topic; setup lessons may take one afternoon.
What if I get stuck on useRef?
Re-read the line-by-line walkthrough, check the browser console for red errors, and compare your code character-by-character with the example. Search the exact error text — someone else had it too.
Where is useRef used in real jobs?
See the real-world section above — the same pattern appears in LMS, banking, e-commerce, and SaaS products. Interviewers ask you to explain it using one concrete example from your project or this lesson.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!