3 ms·
As I said, you don't need contexts for this, signals can be completely global, and in the example I gave the signals were global (you don't even really need the
by MrJohz 3y ago
As I said, you don't need contexts for this, signals can be completely global, and in the example I gave the signals were global (you don't even really need the function).
But the whole point is that "simple, easy to understand" is very context-dependent. Goto, for example, is very simple, possibly the simplest form of control flow you can imagine, and it's also easy to understand at the point that you're writing it down. It just moves control flow to where you want it to go - what could be simpler than that?
But simplicity needs at least some structure, otherwise it becomes chaos. That's the value of encapsulating both the events and the state in a single place, and then providing a limited interface to that reactive state. Yes, it's (slightly) more up-front work to write that interface out explicitly, as opposed to just putting things into events, but it has real value later on when someone else needs to read the code and understand what it's going to do.
- andrewstuart 3y agoI 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.