Document_useRef
Document_useRef
1. What is it?
useRef is a React Hook that lets you reference a value that’s not needed for rendering.It allows us to
store values that are mutable but doesn't cause re-render.
While working with forms and you want to focus on your text field on any error or when we load the
page we can make use of useRef hook to refer to that particular DOM element.
For example:
useEffect(() => {
inputRef.current.focus();
}, []);
return (
<>
</>
);
One of the benefit's of useRef hooks is that changes to it doesn't trigger re-renders of the component.
This makes useRef an excellent choice for storing values that you want to persist across re-renders but
don't want to cause re-rendering.
4. When do I use it?
UseRef are mostly use when you want to access and manipulate the DOM or store mutable values
without triggering re-renders.
useEffect(() => {
console.log("Re-render");
});
function handleClick() {
ref.current = ref.current + 1;
function handleClickB() {
setValue(value + 1);
return (
<>
);
Output:
Initial Render: