
Useref in ReactJS
✅ useRef in ReactJS
useRef
is a React Hook that provides a way to create and manage references to DOM elements or mutable values without causing re-renders. It is primarily used for accessing DOM nodes and persisting data across renders.
📌 Why Use useRef
?
Access DOM Elements → Directly interact with DOM nodes like inputs or divs.
Maintain Mutable Values → Store values without causing component re-renders.
Hold Previous Values → Track previous state or values without using state variables.
Avoid Re-Renders → Useful for keeping variables that don't affect the UI.
📌 Syntax
<div> <div> import React, { useRef, useState } from 'react';const TimerExample = () => { const [count, setCount] = useState(0); const intervalRef = useRef(null); const startTimer = () => { if (!intervalRef.current) { intervalRef.current = setInterval(() => { setCount((prevCount) => prevCount + <div> import React, { useRef, forwardRef, useImperativeHandle } from 'react';const ChildComponent = forwardRef((props, ref) => { <h1>{message}<div> <ChildComponent ref={childRef} /> <button onClick={handleChangeMessage}>Change Message</button> </div> );};export default ParentComponent;
🛠 Explanation:
forwardRef()
allows passing refs to child components.useImperativeHandle()
exposes methods likechangeMessage
to the parent component.
📌 5. When to Use useRef
?
✅ Use useRef
when:
You need to directly manipulate a DOM element.
You want to store mutable values without causing re-renders.
You are implementing timers, animations, or event listeners.
You need to persist data between renders without state management.
❗ Avoid useRef
when:
State needs to trigger UI updates — use
useState
instead.You are managing complex state logic — use
useReducer
.
📌 6. Conclusion
useRef
is an efficient way to manage references to DOM elements.It is often used in forms, timers, animations, and maintaining previous state values.
It prevents unnecessary re-renders, improving performance.