What is useRef: The useRef hook allows to persist values between renders. This can be used to store a mutable value that does not cause a re-render when it is being updated. This can be used to access a DOM element directly.
Syntax:
import { useRef } from "react";
const ref = useRef(initialValue);
If we use the useState Hook to count how many times our app renders, it will keep re-rendering endlessly — because updating state itself causes another render.
To prevent this infinite loop, we can use the useRef Hook instead, since changing a ref does not trigger re-renders.
Why useRef?
- To access DOM elements directly. This lets you to get a reference to a DOM element (like an or ).
- To store mutable values without re-rendering.
- To keep track of previous values. useRef can remember a value from previous render.
Ex:
import React, { useRef } from "react";
function App() {
const reference = useRef();
const getText = () => {
console.log(reference.current.value);
};
return (
<div style={{ textAlign: "center", marginTop: "50px" }}>
<input type="text" ref={reference} placeholder="Enter text" />
<button onClick={getText}>Get Text</button>
</div>
);
}
export default App;
Top comments (0)