'using useRef in input to avoid re render in appication

I want to implement useRef so that the component in which my input tag is should not re-render on value change. If we use useState it will re-render the entire component on every key pressed.

This is how we usually do it but this will re-render the entire component on every change.

const [name, setName] = useState('');
return(
   <input type="text" placeholder="Name" value={name} onChange={e => setName(e.target.value)} />   
)

I want to do this using useRef to avoid it

const name = useRef("");
const handleName = (e) => {
   name.current = e.target.value
 };

return(
   <input type="text" placeholder="Name" value={name.current.value} onChange={handleName} />   
)

but it's not working for some reason?



Solution 1:[1]

Change your input tag to this (inside JSX):

     <input type="text" placeholder="Name" ref={name} onChange={handleName} />   

Instead of value={name.current.value} use ref={name}. It should fix the issue.

Full code :

import { useRef } from "react";

export default function App() {

  const name = useRef('');

  const handleName = (e) => {
     name.current = e.target.value
     document.getElementById('test').innerText = name.current
   };
  
  return(
    <>
     <input type="text" placeholder="Name" ref={name} onChange={handleName} />   
     <p id='test'></p>

     </>
  )
  
}

Solution 2:[2]

if you want to avoid rendering on change, you can just pass ref to the input element. and whenever required you can get the value from ref as used in the handleSubmit method below. Html input element will maintain its state:

    const nameRef = useRef(null);
const handleSubmit = () => {
  console.log(nameRef.current.value);
};

return(
   <input type="text" ref={nameRef}  placeholder="Name" />   
)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2