I need to be able to track number of instances of my component, how do I do that in React using functional components?
I tried to use useRef()
but it seems like even though it preserves the value between the renders - it does not share the value between the component instances.
So far the only solution I came up with is this sily one, I hope there is a way to store it somehow in more elegant way.
const [ ident, setIdent ] = useState(0);
useEffect(() => {
if (document.sometring === undefined) {
document.sometring = 0;
} else {
document.sometring++;
}
setIdent(document.sometring);
}, []);
Update to the question: The use case is more actademical, I want to know how to do it, rather than practical. I want every instance of my independent component to have unique sequential ID (like "button-42") so this is why solutions like "give it a random code" also won't work for me. Global state managers like redux or context also cannot be a solution because, let's say, If i open-source my component on GitHub I should not ask users to install also redux or use React.Context. And of course this ID should not change if component re-renders.