React & Modern Frontend (445 Qs)•Part 8: Advanced React Patterns, Portals & Performance (152 - 261)
What is the difference between useState and useRef hook?
- useState causes components to re-render after state updates whereas useRef doesn’t cause a component to re-render when the value or state changes.
Essentially, useRef is like a “box” that can hold a mutable value in its (
.current) property. - useState allows us to update the state inside components. While useRef allows referencing DOM elements and tracking values.
Practical Code Example
jsx
// useState vs useRef:
function StateVsRef() {
const [count, setCount] = useState(0); // Changing triggers re-render!
const renderCount = useRef(0); // Changing does NOT trigger re-render!
useEffect(() => { renderCount.current++; });
return <button onClick={() => setCount(count + 1)}>Count: {count}</button>;
}