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

How to use Set with useRef?

I am trying to use Set with useRef. This is what I tried.

export default function App() {
  const data = useRef<Set<string>>(new Set());

  const add = () => {
    data.current = new Set([...Array.from(data.current), "Add"]);
  };

  const show = () => {
    console.log(data.current);
  };

  return (
    <div className="App">
      <button onClick={add}>Add</button>
      <button onClick={show}>Show</button>
    </div>
  );
}

I am getting Set {} when I check the value after updating. What is actually going on here?

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

>Solution :

Your code is actually working correctly. The Set {} is just the way the console shows a set. You can see upon expand (after clicking add then show), the data is there.

The other answer about adding to the set rather than the complex spread is also true btw — you dont need to care about immutable state transitions with refs. But this is a code smell rather than a bug. Your code still works.

enter image description here

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