Nearby lessons
18 of 43🪝 ReactJS – useRef Hook & Uncontrolled Components
📌 What is useRef?
What is useRef Hook in React?
The useRef Hook allows you to persist values between renders without causing re-renders.
It can also be used to directly access DOM elements in functional components.
An uncontrolled component uses refs instead of state to manage form inputs.
📌 Why use useRef?
- Access DOM elements directly using
refattribute - Store a mutable value that does not cause re-render
- Persist values across component renders
- Helpful for uncontrolled components (like forms without state)
⚙️ Accessing DOM Elements with useRef
We can attach a ref to any element to access it directly in the DOM.
Here, we use useRef with <h1> and change its style dynamically.
📝 Uncontrolled Component with useRef
Instead of storing form values in useState,
we can use useRef to directly read values from input fields.
❌ Problem: Using useState for Render Count
If we try to use useState inside useEffect
to count renders, it causes an infinite loop.
✅ Solution: Using useRef for Render Count
We can fix this issue by using useRef instead of useState
since updating ref.current does not trigger re-renders.