When we should use useRef instead of useState?
For some specific use cases where we should use useRef over useState
1. Use useRef
to optimize performance when frequent updates would cause unnecessary re-renders.
function MouseTracker() {
const mousePosition = useRef({ x: 0, y: 0 });
const handleMouseMove = (e) => {
mousePosition.current = { x: e.clientX, y: e.clientY }; // Update without re-rendering
};
useEffect(() => {
window.addEventListener("mousemove", handleMouseMove);
return () => window.removeEventListener("mousemove", handleMouseMove);
}, []);
return <p>Move your mouse and check the console for updates.</p>;
}
2. When working with form and the value of input only needed when the form is submitted.
import React, { useRef } from "react";
function FormWithRef() {
const emailRef = useRef(null);
const handleSubmit = (e) => {
e.preventDefault();
const email = emailRef.current.value;
console.log("Email:", email);
emailRef.current.value = "";
};
return (
<form onSubmit={handleSubmit}>
<div>
<label>
Email:
<input type="email" ref={emailRef} />
</label>
</div>
<button type="submit">Submit</button>
</form>
);
}
export default FormWithRef;