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
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
becomes3
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 theval
state. Then, it will display3
and the next effect will run after that.Try adding an empty dependency array to the useEffect call:
Let me know if this works.