Home > Back-end >  How to use Set with useRef?
How to use Set with useRef?

Time:08-12

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?

CodePudding user response:

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

CodePudding user response:

As was said in the comment by super

A ref doesn't have any automatic updating, so you don't need to recreate the object. Just add to the existing set.

const add = () => {
  data.current.add("Add");
};
  • Related