React- how would you go on organize common event listeners for separate components

After my last project which aim was for me to get more familiar with react, an issue caught my attention. Many of my components were relying on identical event listeners, yet those components were not directly related on the tree. For example one page had a tooltip which was relying on screen resize and screen scroll. The navbar had also menus relying on resize and scroll. Another button on another page also had its functionality related on resize and scroll. Basically i had several separate handlers for scroll and resize working for different components, which seems quite poor design. When i look on the net, all i find is guides on how and where to define event listeners, but no word on this matter. How would you go on define one global event listener, say for resize, that will send calls to components that depend on that? Few issues i can think of are, first ill need to have a way to link all those components(callback/redux); some of the components might not be rendered/existing on the page, so they wont require the handler to hand them data; there could be an issue when the listener is trying to refer to a component which does not even exist…

1 Like

for nav bar resize, I assume you wanted it to change for smaller screens? Why not use media queries with breakpoints?

Yes redux would be a good idea if you want to do it via state accessible on all components.

IMO you need to take a step back and find out what the problem is specifically and break it down. Don’t be afraid to spend time on design/thinking since it’s crucial to how your app ends up being coded.

your assumption is wrong, i do use media queries to make my page responsive and the nav bar does change its appearance and size with breakpoints, but there are functionalities i need to handle within JS.
On my next project, i am going to try define universal listeners for resize and scrolling and subscribe to them components which require their data, but i havent figured it out yeat in my head and i was hoping people already encoutnered similar situation and have some good practices(im sure im not the only one who could use same event listeners on more than one components). Ive already spent far more time on my last project than i was anticipating and continue to do, creating new problems for myself and tackling them, so im in no way afraid to invest the extra time :slight_smile: