Hacker News new | ask | show | jobs
by chrismorgan 1491 days ago
The URL is global state. Only one thing can use it to control what’s displayed. It is an error to manipulate `location` or `history` at the widget or library level: they must only be used at the application level.

Passing history in as a property doesn’t solve anything in the application: it’s still global state, and if multiple things try to use it (even if one is trying to use the hash and the other the path), they’ll interfere with each other and you’ll have a bad time.

Passing it as a property may help with mocking-based test frameworks (though I find mocking to normally be a bad technique—you get better results from unit tests and integration tests with real systems), though you may also be able to control the global variables to accomplish the same effect; yet as far as the application is concerned, it’s still global state.

So then: since anything working with the URL is unavoidably working with global state, I see no virtue in avoiding a global event handler.

1 comments

Global state is never actually necessary. Functional programming doesn't require global state to be turing complete. So I don't see what you mean by it being unavoidable. Passing it in makes it not global state anymore. As I explained in the mocking example. You can run multiple tests at once while initializing a different mock History object to be passed in for every test.

In my experience, generally when people try to use global handlers, it ends up getting bloated as more and more teams add their quirks and features into those handlers. There are numerous ways to mitigate this but I've found that the easiest way to prevent these issues is to simply move the logic into components. And React context gets rid of the need for prop drilling and removes most of the boilerplate involved with passing data to deeply nested components.