skip to Main Content

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 –

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

2

Answers


  1. 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.

    Login or Signup to reply.
  2. Try adding an empty dependency array to the useEffect call:

      comRef.current = comRef.current + 1;
    }, []);
    

    Let me know if this works.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search