by treis · 3y ago · 0 comments
>Things get more complicated when you start using React Context and start signalling updates in a parent component. The render cascades. Maybe one component fetches some data, some component remounts, and you run your state update again, delayed by a few seconds.
This is just doing it wrong. State should change in response to user inputs. Ultimately, React is f(newState) => UI. If that function isn't pure you're gonna have a bad time. It's hard to blame anyone though. The docs suck and most of the tutorials you find get it wrong one way or another.
That said, there's kind of a reason why functional programming isn't more popular. It can be hard to grok and there can be a significant performance overhead. There's also a reason why this sort of implicit programming isn't as popular as imperative style. It's hard to predict what the implicit behavior is and footguns abound.
The bit that is g(state, userInput) => newState is the hard part. In particular managing the scope of that newState.
Oh, and sometimes you need to handle h(state, asynchronousData) => newState too.
And then comes the fact that even though your f is _pure_, it also has to be _fast_, because it's going to run every time you get a newState.
It's like you're speaking a different language to me, and I find that so weird considering we're using the exact same framework. How am I not having any of these issues?
I'm honestly at the point where I wonder if y'all are making things harder on yourself somehow, because I could see how getting obsessed with counting every single re-render and trying to overoptimize would result in the stuff you're saying while not actually impacting perf in a meaningful way.
When I do encounter a component with countless re-renders as described, it is usually painfully obvious what causes them and easy enough to fix.
I think we're going too far if we're expecting React, or any framework, to be fool-proof to the point that we can just throw "whatever" we want at them and expect it to have peak performance.
Timing-based UIs are (such as a sequence of triggered animations) can get really messy really fast. I've seen some really messy bugs in a app that had visuals and audio tied to different timers and user inputs in the app. We eventually moved all time-based animations to observables, which helped some
Something I don’t quite get, doesn’t useRef just solve the re-render issue?
I had to eventually claw my eyes out and that solved part of my problems, at least I did not see the boilerplate and the ugliness.
Then soon after that we worked on a similar thing (form + draggable carousel with snap to grid animation) in Angular with Material.
And my conclusion is that whichever framework you pick, whatever libraries you end up using, you must have a strategy to allocate your time and maintenance budget, and many many many times the sane compromise is to write something in raw JS and encapsulate that in whatever the framework gives you, and move on. Don't try to solve it within the framework, because it's just not worth it.
I don't know if we have any "timing" based components, though we manage global state using Apollo Client and again, haven't really had any issues with that.
- https://redux.js.org/usage/side-effects-approaches#recommend...
What I like about sagas are their simplicity & power (once one understands how generators & effects work), plus the eventChannel feature which lets one integrate with non-redux events. Good TypeScript support is a problem though, and I've had to resort to typed-redux-saga :/
Sagas keep state (and you should keep most state in the redux store, anyway).
So, yes, you can go wrong, as with everything else. But it's better than using useEffect as an async framework.
Remove most logic from the components into sagas,thunks and selectors.
That way your components will be smaller, more testable, easier to change, easier to reason about.
Your app is the store, not the DOM.
It really makes things much simpler. The trick is to keep all the state in the store, including when things are loading, when some user interaction is happening but not yet complete, etc.
From your comment, it seems like there may be some problem if the user is interacting somehow, let's say in the middle of doing a drag and drop, and some data update comes in from a websocket, right? Well, if that's going to cause a problem for your render it's because apparently your data-updated function h needs to know if the user is doing a drag and drop. That should get put in the state when the user starts the interaction, and now h can know about it and react correctly.
Yes, it's more complicated than just have some component render based on the data you receive, but that's because it turned out that your app was more complex than you thought, it has more states you need to care about.
There's no magic wand, but this stuff works, just adds some boilerplate code but I don't mind.
Didn't have to in the past. Back with class-based components we had shouldComponentUpdate(), and lost that when components switched to pure functions.
The clue is in if everyone is missing the point but you, may be start with more introspection. :)
I will give an example of a side project I am working on. The homepage has two sub components, one when the user is logged in, one when the user is logged out.
Now, when the user logs in, the state of the homepage parent component needs to change, the state of the nav bar needs to change etc.
Your problem is in assuming newState is completely described locally which isn't always the case.
React is not that at all. Unless your UI is very simple, React is not f(newState) => UI. React isn't functional. More on that here: https://mckoder.medium.com/why-react-is-not-functional-b1ed1...
The complicated bit is the handling of events and changing the state. Hence why you get Redux for state but there is no “Redux for views”
It's not wrong, it gives you one kind of separation of concerns: components. But "the view is a function of state" is completely misleading IMO.
> But then they added hooks and useState and useEffect and so on, which made the functions impure. The problem with hooks is that they “hook into” React state and lifecycle features, which means it is modifying global state.
React components don’t update the dom every time they run, they update the fiber tree / virtual DOM.
Only in the commit phase is the DOM updated and side-effects are run.
My rough understanding is that:
Hooks, excepting useEffect, all run in the render phase.
UseState hooks store data in the component in the fiber tree, and capture a sequential list of updates when you call setState.
Algebraic effects can seem a bit odd at first, but it’s really like a generalised try/catch. Instead of storing state in the function itself, you reach out up the stack to the component and store it there. And every hook you call from your hook stores it there too.
It’s why call order is important, because it’s how they know which is which.
You don’t modify any global state though.
The actual component function needs to be able to be called multiple times in the render phase (which just updates the vdom), and must have the same output each time, if the inputs/props are the same.
Every now and then, the tender phase can be interrupted to run the commit phase, which synchronously brakes a snapshot of the vdom and applies all the needed updates to the outside world.
Perhaps it’s better to think of as
render: f(props) -> descriptionOfUI commit: apply(descriptionOfUI)
I would absolutely say components and hooks are functional, with algebraic effects. And that the resulting data struct from those components, is what’s used to produce side effects.
Even useEffect, is a description of a side effect to run, it doesn’t run in your hook, it runs on commit with all the other side effects.
There’s a ton of optimisations under the hood but that’s roughly my understanding of how it works.
In functional programming, functions are not allowed to do that. The only thing a function is allowed to do is return a value.
> ...you reach out up the stack to the component and store it there.
FP functions are not allowed to do that. In FP functions can only rely on the parameters passed to it (it cannot refer to anything outside) and it should not do anything beyond return a value.
> It’s why call order is important, because it’s how they know which is which
In FP, functions can be called in any order (unless one function needs the return value of another), and the final result is not affected by the order.
> You don’t modify any global state though.
If you have state it is not FP, whether it is global or not.
function MyComponent({}) {
const [count, setCount] = useState(0);
const [active, setActive] = useState(true);
useEffect(() => if (active) setTimeout(1000, () => setCount(count+1)), [count, active]);
...
can kind of be thought of as if it accepts an extra hidden set of parameters, kind of like this: function MyComponent({}, hook1 : useState, hook2 : useState, hook3 : useEffect) {
const [count, setCount, hook1Result] = hook1(0);
const [active, setActive, hook2Result] = hook2(true);
const hook3Result = hook3(() => if (active) setTimeout(1000, () => setCount(count+1)), [count, active]);
...
return [<div></div>, [hook1Result, hook2Result, hook3Result]];
}
In this version, those hook functions are side-effect free, pure functions that our caller provides us with, closed over the previous stored state of our component in the tree; and when we return the results along with our rendered output, our caller has the new state of our component together with our desired DOM.Instead of forcing us to write all that extra code, route those extra variables, and figure out the metadata mechanism whereby the caller of the render method figures out what hook functions to supply, the rules of hooks let you use JavaScript's imperative, procedural syntax to call hooks which are implemented using ugly side-effecting impure techniques, but in a way that pulls off something semantically identical to this pure functional flow.
It's a pretty neat trick, honestly.
Oh, yes, they are allowed to do that. You capture the effects into a list, and return the tuple of list and return value. If you feel like it, you wrap that into a monad to pretend you are only "returning" a single thing.
> In FP functions can only rely on the parameters passed to it (it cannot refer to anything outside) and it should not do anything beyond return a value.
You mean explicit parameters (props) and implicit parameters (context), right? I thing you forgot the latter. Implicit parameters have existed for quite a bit, for example in the reader monad.
> In FP, functions can be called in any order (unless one function needs the return value of another), and the final result is not affected by the order.
Yup, except if you write a bunch of functions and store them in a list with the intention of applying the result of the first entry of the list against the first entry of the list. Now, if you construct the list of functions as effects (by hiding them behind a monad) you find out that you need to call the effects in the same order as to construct the list of effects in the same order. This doesn't contradict FP, it contradicts your mental model of how React is supposed to work.
> If you have state it is not FP, whether it is global or not.
The state resides in the runtime executor, exactly like Haskell's IO monad. Again, this contradicts your mental model, not React or FP.
useEffect is a side effect and if you use it you're gonna have a bad time.
Right.. but then you can't really use React for building serious UI.
But it’s a powerful escape hatch like rust’s `unsafe` block. Rust can do amazing things to ensure safety of your program, but there’s still times where a human can do it better.
By signposting that, keeping it to limited blocks, and wrapping it up in a safe function you get the capability to do hard things, while exposing a safer API.
useEffect is similar, it lets you write the imperative synchronisation logic. For example if you need to interact with a DOM element that only has an imperative API, someone needs to do the work somewhere to wrap it in a declarative one. You can do that in a component with a useEffect hook, and then expose a declarative API.
Why would fetching data depend on whatever is being rendered?
You know what data you need or not need before rendering anything, or you will be in a world of pain.
function handleChange(e){
getAutoSuggestions()
setLoadingState(true)
}^ Side effects happen in response to user input
function getAutoSuggestionsCallback(resp){
setSuggestions(resp)
setLoadingState(false)
}^ No side effects
Absolutely not only to user inputs, but any kind of event: response, websockets, push notification, worker task finished... a million things beyond the basic "click".
> If that function isn't pure you're gonna have a bad time.
Hooks let you deal with "component lifecycles" which make that function not pure. Only the most basic toy react components are pure, everything is about side effects IN your views.