Nearby lessons
22 of 44⚛️ ReactJS – useRef & Uncontrolled Components
📌 What is useRef?
What is useRef? Why do we use it in React?
The useRef hook is used to directly access and manipulate DOM elements or to store
mutable values that persist across renders without causing re-renders.
In React, we can add a ref attribute to an element to access it directly in the DOM.
Uncontrolled components rely on refs instead of state for handling form values.
📌 What is useRef?
- It can be used to access a DOM element directly
- It can be used to store a mutable value that does not cause a re-render when updated
- We can use
useRef()in function components for the ref purpose - In uncontrolled components, refs are used instead of state to get form values
⚙️ Accessing DOM Elements
We can assign useRef() to an element’s ref attribute.
This gives us direct access to the DOM node.
import React, { createContext } from 'react'; import UseRefHook from './UseRefHook.jsx'; const App = () => { return ( <div> <UseRefHook/> </div> ); } export default App;
🧩 Uncontrolled Form Example
Instead of using useState for every input, we can use useRef to
directly read form values when needed.
import React, { createContext } from 'react'; import UseRefHook from './UseRefHook.jsx'; const App = () => { return ( <div> <UseRefHook/> </div> ); } export default App;
❌ Problem with useState (Re-render Loop)
Using useState to count renders inside useEffect with empty dependency
causes unwanted behavior or infinite loops.
export default function App() { return ( <div> <h1>Hello React!</h1> </div> ); }
✅ Solution with useRef (No Re-render)
Using useRef avoids re-renders while still keeping values persistent
between renders.
export default function App() { return ( <div> <h1>Hello React!</h1> </div> ); }