dhanushkac
dhanushkac

Reputation: 550

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?

Upvotes: 0

Views: 593

Answers (2)

Konrad
Konrad

Reputation: 24691

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");
};

Upvotes: 0

adsy
adsy

Reputation: 11597

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

Upvotes: 1

Related Questions