I made a custom hook that registers data into a store keyed by the components that use it, and then removes the data from the store when the components unmount. Basics are like this
const [id] = useState(Math.random());
const setData = useCallback((data) => {
if(data) {
setRegistrations({
...registrations,
[id]: data
});
} else {
const {[id]: _, ...nextRegistrations} = registrations;
setRegistrations(nextRegistrations);
}
}, [id]);
useEffect(() => {
// update the registration if the data changed
setData(data);
}, [data, setData]);
useEffect(() => {
// remove the registration on unmount
setData();
}, []);
I'm using Math.random()
to generate a unique id for each component that uses my hook, and that works fine, but I was hoping there's a way to figure out the name of the component that is using my hook. It'd make debugging my application state easier if I could see which data was registered by which component, but instead all I have to look at is a random decimal.
Right now my store looks like this
{
'0.5694216823063629': { ... }
'0.002760497537984463': { ... }
}
I'd prefer if I could do something like this
{
'MyComponent-1': { ... }
'MyComponent-2': { ... }
'MyOtherComponent-1': { ... }
}
Yes, I know I could just make components pass in a key, but that's missing the point. I want the API to remain pure and not pollute it just so debugging is easier.
Is there a way to figure out which component used my hook?