using react's ref today can be a little confusing.
back to the days of class components, it was very clear in the docs.
we should use refs mostly for DOM elements :
https://reactjs.org/docs/refs-and-the-dom.html
But today we have hooks together with functional components.
and we are using useRef
hook.
also, this brings to us new patterns. using ref to contain callbacks, or any data we want to preserve (kind of state) but without the need to rerender.
its a powerful API and also shows up in the docs:
https://reactjs.org/docs/hooks-faq.html#is-there-something-like-instance-variables
so now ref can be used for:
store mutable data
kind of memoization
but these docs contradict each other. and causing many mistakes, and conflicts in development teams.
the doc says 2 different things and its a problem.
so, what is the right thing to do in a scenario like that?
const MyComponent = (props) => {
const [myMap1, _] = useState(new Map()); // 1.
const myMap2 = useMemo(()=> new Map(), []); // 2.
const myMap3 = useRef(new Map()); // 3.
...
};