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?
>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.
