I have a functional React component (more a proxy to a non-React object) like so:
function ProxyComponent({onEvent1, onEvent2, onEvent3 ...}){
useEffect(()=>{
someObject?.on('event1', onEvent2);
return someObject?.off('event1', onEvent2);
},[onEvent2, someObject])
useEffect(()=>{
someObject?.on('event1', onEvent1);
return someObject?.off('event1', onEvent1);
},[onEvent1, someObject])
.
.
.
}
Except that there are a lot of events, and there's an obvious pattern here. So I'd like to do this:
function ProxyComponent(props){
const events = {
'event1': props.onEvent1 ?? null,
...
'event20': props.onEvent20 ?? null
}
for (const [name, handler] of Object.entries(events)) {
useEffect(()=>{
handler && someObject?.on(name, handler);
return handler && someObject?.off(name, handler);
},[handler, someObject])
}
}
The rules of hook make it clear that this usage is not supported, but I'd like to know how I can automate this pattern while still being within the rules of hook [This is the main question]
Notes:
The
.onand.offmethods create network requests so it's best to call them as little as possible.Moving the loop inside the useEffect creates two complications:
a. A very long dependency array [onEvent1, ..., onEvent20]. I highly doubt that
[...Object.values(events)]works.b. Every change in a single handler causes several
.offs and undoes it with new.ons again. Apart from the inefficiency, in my particular case, I'd like to avoid this because of note#1.