-4

When add name is clicked the idRef is incrementing 2 times instead of 1 time. the output is shown below

const { useRef, useState } = React;
function UseRefs() {
  const inputRef = useRef(null);

  const idRef = useRef(1);
  const [names, setNames] = useState([]);

  const addName = () => {
    setNames((prevNames) => [
      ...prevNames,
      { id: idRef.current++, name: inputRef.current.value },
    ]);
  };

  return (
    <div>
      <div >
        {names.map((name) => (
          <div key={name.id}>
            {name.id}. {name.name}
          </div>
        ))}
      </div>
      <div className="m-3">
        <input type="text" ref={inputRef} />
        <button  onClick={addName}> Add name </button>
      </div>
    </div>
  );
}

ReactDOM.createRoot(document.querySelector('.react')).render(<UseRefs />);
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<div class='react'></div>

OUTPUT:

1 a, 3 ab, 5 ABC, 7 abcd

EXPECTED

  1. a
  2. ab
  3. abc
  4. abcd

output image

Dustin Bun
  • 13
  • 2

1 Answers1

0

It's happening because react is rendering the component UseRefs twice.

This is due to the <React.StrictMode> is enabled by default when creating react app with npx create-react-app.

details are shown here https://stackoverflow.com/a/61897567/16958718

Dustin Bun
  • 13
  • 2