| useCallback in React :👈 | 👉:Custom Hooks in React |
useRef vs useState: Key Differences |
useRef vs useState: Key Differences in React
1. Quick Answer
Both useRef and useState are React Hooks that allow functional components to retain values between renders. However, they serve different purposes.
- useState: Stores data that affects the UI. Updating state schedules a re-render.
- useRef: Stores a mutable value that persists between renders. Updating
ref.currentdoes not trigger a re-render.
Simple rule: Use useState when a value needs to update the UI. Use useRef when you need to remember a value without triggering a re-render, or when you need to access a DOM element.
2. Table of Contents
- Understanding useState
- Understanding useRef
- Key Differences
- Example: Updating a Counter with useState
- Example: Storing a Value with useRef
- Example: Accessing a DOM Element
- Example: Storing a Timer ID
- Can You Use Both Hooks in One Component?
- Common Mistakes
- Performance Considerations
- Best Practices
- Interview Questions
3. Understanding useState
useState is a React Hook used to store and update component state. When you update the state using its setter function, React schedules a re-render so the UI can reflect the new value.
Syntax
const [value, setValue] = useState(initialValue);
valuerepresents the current state value for the render.setValueis the function used to update the state.initialValueis the initial state value.
Example: Counter Using useState
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
</div>
);
}
export default Counter;
How It Works
- Initially,
countis0. - When the button is clicked,
setCountrequests a state update. - React renders the component again with the updated state.
- The UI displays the new count.
Important: State updates are scheduled by React and may be batched. The state variable in the current render does not immediately change when you call its setter.
4. Understanding useRef
useRef is a React Hook that returns an object with a current property. The same ref object is retained across renders of the component's mounted instance.
Syntax
const ref = useRef(initialValue);
You can access or update its value through ref.current.
Example: Storing a Value with useRef
import { useRef } from "react";
function Counter() {
const countRef = useRef(0);
function increment() {
countRef.current += 1;
console.log("Count:", countRef.current);
}
return (
<div>
<button onClick={increment}>
Increment
</button>
</div>
);
}
export default Counter;
How It Works
- Initially,
countRef.currentis0. - Each button click increments the stored value.
- The updated value persists between renders.
- Changing
countRef.currentdoes not trigger a re-render.
Notice: This example does not display the count in the UI. If you add {countRef.current} to the JSX, changing the ref alone will not update the displayed value. The component needs another render before React can display the latest value, and reading mutable refs during rendering is generally not an appropriate way to manage UI state.
5. Key Differences Between useRef and useState
| Feature | useState | useRef |
|---|---|---|
| Primary purpose | Stores data used to render the UI | Stores mutable values that do not themselves drive rendering |
| Triggers re-render | State updates schedule a re-render | Changing ref.current does not trigger a re-render |
| Accessing the value | Read the state variable directly | Read or update ref.current |
| Updating the value | Use the setter function | Assign a new value to ref.current |
| UI updates | Suitable for values that must appear in the UI | Not suitable by itself for values that must immediately update the UI |
| DOM access | Not the usual approach for DOM references | Commonly used to reference DOM elements |
| Typical examples | Form values, counters, selected tabs, loading indicators | DOM elements, timer IDs, previous values, mutable instance information |
| Persistence | State is retained across renders while the component remains mounted | The ref object and its current value are retained across renders while the component remains mounted |
6. Example: Updating a Counter with useState
Use useState when the displayed value must change after an interaction.
import { useState } from "react";
function StateCounter() {
const [count, setCount] = useState(0);
return (
<div>
<h2>Counter: {count}</h2>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
</div>
);
}
export default StateCounter;
Result: When you click the button, the displayed count increases because the state update schedules a re-render.
7. Example: Accessing a DOM Element with useRef
One of the most common uses of useRef is accessing a DOM element, such as an input field, to focus it programmatically.
import { useRef } from "react";
function FocusInput() {
const inputRef = useRef(null);
function handleFocus() {
inputRef.current?.focus();
}
return (
<div>
<input
ref={inputRef}
type="text"
placeholder="Enter your name"
/>
<button onClick={handleFocus}>
Focus Input
</button>
</div>
);
}
export default FocusInput;
How It Works
useRef(null)creates a ref object.- The
ref={inputRef}attribute tells React to place the DOM input element ininputRef.currentwhen the element is mounted. - When the button is clicked,
handleFocuscallsfocus()on the input element.
Result: Clicking the button moves the cursor into the input field without requiring a state update.
8. Example: Storing a Timer ID with useRef
Suppose you want to start and stop an interval. You need to retain the timer ID so that you can clear the interval later. The timer ID does not normally need to be displayed in the UI, making useRef a suitable choice.
import { useRef, useState } from "react";
function Timer() {
const [seconds, setSeconds] = useState(0);
const intervalRef = useRef(null);
function startTimer() {
if (intervalRef.current !== null) {
return;
}
intervalRef.current = setInterval(() => {
setSeconds(previous => previous + 1);
}, 1000);
}
function stopTimer() {
if (intervalRef.current !== null) {
clearInterval(intervalRef.current);
intervalRef.current = null;
}
}
return (
<div>
<h2>Seconds: {seconds}</h2>
<button onClick={startTimer}>
Start
</button>
<button onClick={stopTimer}>
Stop
</button>
</div>
);
}
export default Timer;
Why Use Both Hooks?
useStatestoressecondsbecause the displayed timer must update.useRefstoresintervalRef.currentbecause the interval ID is needed for controlling the timer but does not need to be displayed.
Production consideration: A timer should also be cleaned up when the component unmounts. An effect with a cleanup function is a suitable way to manage this lifecycle. The example above focuses on demonstrating the difference between state and refs.
9. Can You Use Both Hooks in One Component?
Yes. In fact, using both hooks together is common when a component needs to display some data and retain other information that does not directly affect the UI.
Example
import { useRef, useState } from "react";
function ClickTracker() {
const [visibleCount, setVisibleCount] = useState(0);
const totalClicksRef = useRef(0);
function handleClick() {
totalClicksRef.current += 1;
setVisibleCount(visibleCount + 1);
console.log(
"Total clicks recorded:",
totalClicksRef.current
);
}
return (
<div>
<p>Visible count: {visibleCount}</p>
<button onClick={handleClick}>
Click Me
</button>
</div>
);
}
export default ClickTracker;
Explanation
visibleCountis state because its value is displayed in the UI.totalClicksRef.currentis a ref because it is used to retain a mutable value without independently triggering a re-render.- Clicking the button updates the state, which causes a render, and increments the ref value.
In this particular example, both values increase together. The ref is useful for demonstrating the difference, but in a real application you should choose a ref only when the value genuinely does not need to drive rendering.
10. Common Mistakes
Mistake 1: Using useRef for Data That Must Update the UI
Incorrect approach:
const countRef = useRef(0);
function increment() {
countRef.current += 1;
}
If the UI displays countRef.current, updating it will not trigger a render. The displayed value may remain unchanged.
Better approach:
const [count, setCount] = useState(0);
function increment() {
setCount(previous => previous + 1);
}
Use state when the updated value needs to be reflected in the UI.
Mistake 2: Expecting useState to Update Immediately
Incorrect expectation:
const [count, setCount] = useState(0);
function increment() {
setCount(count + 1);
console.log(count);
}
The logged value is from the current render. Calling setCount does not change the value of count inside that already-running function.
Better approach when the next value depends on the previous value:
setCount(previous => previous + 1);
This functional updater helps avoid calculations based on an outdated state value when multiple updates are queued.
Mistake 3: Reading or Writing Refs During Rendering
Changing or reading mutable ref values during rendering can lead to unpredictable behavior. In general, read or update refs in event handlers, effects, or other appropriate non-rendering code. Initializing a ref with its initial value is fine.
Mistake 4: Assuming useRef Persists After Unmounting
A ref persists across renders of the same mounted component instance. When the component unmounts, its ref is no longer retained by that component. If the component mounts again, a new ref object is created.
Mistake 5: Using a Ref When State Is More Appropriate
Do not choose useRef simply because it avoids re-renders. If a value affects what the user sees, state is usually the appropriate choice. Avoiding a required render can make the UI incorrect.
11. Performance Considerations
- useState: Updating state schedules a render. This is necessary when the UI needs to reflect the new value.
- useRef: Updating
ref.currentdoes not schedule a render, so it is useful for values that do not directly affect the UI. - Do not optimize prematurely: Avoid replacing state with refs solely to reduce renders. First determine whether the value should be part of the rendered UI.
- Use memoization when appropriate: Hooks such as
useMemoanduseCallbackaddress different performance concerns. They are not replacements for state or refs.
12. Best Practices
- Use
useStatefor values that determine what appears on the screen. - Use
useReffor DOM references, timer IDs, and mutable information that does not need to trigger rendering. - Use functional state updates when the next value depends on the previous value.
- Do not expect changing a ref to update the UI.
- Avoid reading or changing refs during rendering except for predictable initialization patterns supported by React.
- Clean up timers, subscriptions, and other resources when they are no longer needed.
- Do not use refs as a general replacement for React state.
13. Interview Questions
Q1. What is the main difference between useRef and useState?
useState stores state that can trigger a re-render when updated. useRef stores a mutable value that persists across renders, but changing ref.current does not trigger a re-render.
Q2. Does useRef preserve its value between renders?
Yes. React retains the ref object and its current value across renders of the same mounted component instance.
Q3. Can useRef be used to access DOM elements?
Yes. Attach the ref to a supported DOM element using its ref attribute. React sets ref.current to the DOM element when it is mounted and clears it when the element is removed.
Q4. Why does changing ref.current not cause a re-render?
React does not treat changes to ref.current as state updates. The ref is intended to retain mutable information that does not itself determine the rendered output.
Q5. Should you use useRef or useState for a form input?
It depends on the requirement. Use state for a controlled input when React needs to track its current value and render based on it. Use a ref when you need to access the DOM element or read its value imperatively without controlling every change through React state.
Q6. Can useRef replace useState?
No. A ref can store mutable information, but changing it does not trigger rendering. If the UI must reflect a change, state is usually the appropriate choice.
14. Summary
| Requirement | Recommended Hook |
|---|---|
| Display a counter that changes | useState |
| Show or hide a component | useState |
| Track form data that drives the UI | useState |
| Focus an input element programmatically | useRef |
| Store an interval or timeout ID | useRef |
| Retain a mutable value without triggering a render | useRef |
| Update UI based on a changing value | useState |
Final takeaway: Use useState when a change should be reflected in the UI. Use useRef when you need to retain a value across renders without triggering another render, or when you need access to a DOM element. Choose the hook based on the behavior you need, not simply on which one causes fewer renders.
| useCallback in React :👈 | 👉:Custom Hooks in React |
Comments and Discussion