Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Component rerendering count is incorrect while using useRef in ReactJS

I am following a tutorial from the web for learning useRef Hook, which works mostly fine except it is unable to print 2 though after that it behaves normally. Let me know what I am doing wrong here.

In the example code, I want to count the re-render of a component using useRef. Now if you type something in the input box you will notice it won’t render 2 rest all numbers it will print.

Code –

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const InputField = () => {
  const [val, setVal] = useState("");
  const comRef = useRef(1);

  useEffect(() => {
    comRef.current = comRef.current + 1;
  });

  return (
    <div className="fieldset-input-textbox">
      <input type="text" value={val} onChange={(e) => setVal(e.target.value)} />
      <div className="">
        This Component rendered {comRef.current}
        {`${comRef.current > 1 ? " times" : " time"}`}.
      </div>
    </div>
  );
};

export default InputField;

Code Sandbox Link – https://codesandbox.io/s/busy-paper-f2qdhs?file=/src/InputField.js:54-542

>Solution :

You have your root component wrapped in <React.StrictMode>, so during development, React will render the component twice for the initial mount to help catch accidental impurities.

This causes the effect to be run twice, so comRef.current becomes 3 after the component is mounted. Changing refs does not cause rerenders, so this new value is not shown until typing in the text field, which updates the val state. Then, it will display 3 and the next effect will run after that.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading