3 ms·
I do have some level of structure in that the messages are named and prefixed as GLOBAL or LOCAL useEffect(() => { document.addEventListener('GLOBA
by andrewstuart 3y ago
I do have some level of structure in that the messages are named and prefixed as GLOBAL or LOCAL
useEffect(() => {
document.addEventListener('GLOBAL_RELOAD_CHANNEL_INFO', loadChannelInfo)
return () => document.removeEventListener('GLOBAL_RELOAD_CHANNEL_INFO', loadChannelInfo)
}, [loadChannelInfo])
useEffect(() => {
document.dispatchEvent(new CustomEvent('LOCAL_CLOSE_DIALOG_ALL'))
}, [])
useEffect(() => {
const handler = () => setReloadCoverImage(Math.random().toString())
document.addEventListener('GLOBAL_RELOAD_RELOAD_COVER_IMAGE', handler)
return () => document.removeEventListener('GLOBAL_RELOAD_RELOAD_COVER_IMAGE', handler)
}, [setReloadCoverImage])
However when programming React I try to avoid even layers of abstraction beyond what is already enough complexity.
The argument against events is losing track of where they came from and what they do but honestly I found that using state to drive the application UI was vastly more complex and hard to manage and debug than event messages. It's easy to do a global search for GLOBAL_RELOAD_RELOAD_COVER_IMAGE to see what a message does than to trawl your way throw the harrowing complexity and intertwined complexity of state, props, renders and re-renders.
And when I can, I attach the events to local elements in the component rather than document, to further reduce the scope of the complexity.