by ibash · 2y ago · 0 comments
React hooks caused this because by default there’s no sensible place to fetch data.
So unless you know ahead of time, any complex single page ends up with complex and hard to track network requests.
The solution is really simple: pull data out of the view layer and make it a first class citizen.
—
An exercise: imagine you’re building a tui instead of a web app, but you’re forced to use the exact same code for app state and data fetching… what would that code look like?
It prevents the umpteenth reinvention of an incomplete fetch state machine, which is probably the number one most consistent frontend bug I encounter.
I don't understand what it means to "pull data out of the view layer and make it a first class citizen". If you're writing a React app, you are building a UI and will need to handle data in your view layer somewhere. You either hand-off that works to a library like Tanstack Query or you manage it yourself.
UI = f(state)
The problems come when you modify state in response to rendering the UI. This seems deceptively natural (and in fact seems encouraged by on-line tutorials), but leads to "spaghetti fetching" when composing components together - it creates a "feedback loop" that modifies state just because some component happens to mount, which can then modify state further, then cause further mounting/fetching etc...
A better approach is to treat fetching as an explicit state change. If user clicks on a button, you do the fetch and modify the state. If that causes some components to be mounted - so be it, but does not cascade any further.
On the other hand, I can also see some drawbacks:
1. This goes against the idea of fetching data close to where it's used, basically promoting modularization.
2. From the POV of the children, you have to backtrack where their data are coming from.
3. If components always use the same data, you have to duplicate fetching their data everywhere you want to use them.
4. You can't partially show children, but have to wait for everyone to have their data before rendering them.
I feel like there are trade-offs to be made here.Yeah don't do that. Rendering shouldn't have such side-effects. Navigation might, but that's not rendering. Is it a common mistake with React?