by branko_d · 2y ago · 0 comments
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?