14 ms·
Scheduling in React
- tracker1 8y agoThere's definitely some very cool work here... I do think that it's important to remember that the simplest solution is usually the best one to start with. I typically start with redux and redux-thunks with react apps, mostly because I will nearly always hit a point in complexity where it is worth separating state management from the main UI, and thunks is the simplest extension to support async interactions to a server. From there, debounce or concurrent interactions are probably an easier stopgap first. At least until these APIs are distilled a bit, and abstractions make them easier to work with. This can all be summed up with: YAGNI and "Don't prematurely optimize" I've only had a handful of cases where I had to make things more difficult because of behavioral issues in browser applications.
- mephitix 8y ago>> simplest solution is usually the best one to start with. I typically start with redux ?? Redux is definitely not the simplest solution :) I’d argue that starting with local state (which is what hooks seems to be headed towards), then profiling, testing, and adding small amounts of debouncing code where appropriate is more aligned with your sentiment of “don’t prematurely optimize” vs starting with redux.
- atoko 8y agoThen you end up with data fetches being tied to the rendering lifecycle in a way that makes modifying the mechanism painful
- korm 8y agoYou'll eventually need data in the global state in anything but a toy app.
- lilactown 8y agoPutting everything in global state gets really hard to maintain above a medium-sized app.
- korm 8y agoBut... It's not a choice of one or the other, both global and local must be used appropriately. Also the shape of your global state plays a big role in its maintainability and redux provides good tools and documentation to achieve that.
- tracker1 8y agoYou can still slice state into separate reducers and action creators. I use a feature oriented directory structure, so that a given feature may have components/controls, action creators and/or reducers, but not necessarily all of the above. It sounds a little convoluted, but in practice it's made it easier for developers coming in to discover/predict where things are.
- acemarke 8y agoYep. I've settled on a "feature folder" approach myself. When we finally get around to revamping the Redux docs content, I plan on having a "Style Guide" page similar to the one in the Vue docs, which would offer opinionated suggestions with an indication of how important each one is. One of the items I definitely plan to include in there is a suggestion to use feature folders. I also want to reorganize our example apps based on that structure as well. See this issue for details on the docs rewrite: https://github.com/reduxjs/redux/issues/3313 https://github.com/reduxjs/redux/issues/3313
- ergothus 8y agoI too prefer feature folders. I wish it was the example most used...as it is we have a convention that has no reason other than "this how I first saw it done".
- sammorrowdrums 8y agoI generally agree but actually the new hooks allow you to pass certain values down to all children automatically, so I think just hoisting this logic to the highest point that makes sense has this covered to some degree.
- acemarke 8y agoHi, I'm a Redux maintainer. A few thoughts. There's a couple ways to approach building out an app: - Start as small and as simple as possible, and add more pieces down the road once you need them - Determine up-front if you think you'll need various pieces, and get that infrastructure in place at the start . Either of those is a reasonable way to tackle things. As a related note, I'll put in a pitch for our new Redux Starter Kit package. It includes utilities to simplify several common Redux use cases, including store setup, defining reducers, immutable update logic, and even creating entire "slices" of state at once without writing any action creators or action types by hand: https://redux-starter-kit.js.org https://redux-starter-kit.js.org
- pault 8y agoMan, why does every single thread about anything remotely related to react devolve into a flamewar about redux? I wish we could all move on from this tired old debate. Everyone is free to use or not to use redux. If your team uses redux and you hate it, that is not redux's fault.
- whynotminot 8y agoMore often than not you should have a general feel for how complex your app will grow in the medium / near term. If it's going to get beyond "toy" you might as well take the plunge with Redux up front. Starting your design with it is much easier than trying to shoe-horn it in later, even if the cost at the outset feels heavy. If you're fairly confident your app won't get too over the top, then by all means go the easy route!
- tracker1 8y agoNo, it really isn't... but it's a level of complexity that once inherited doesn't get much more complicated as you add more features. It's also imho one of the best options for separating state management. In general, prop drilling is simpler to start with, but quickly turns into spaghetti... you can use the new context options, but they aren't much easier than using Redux at that point, and can become much more complicated.
- quickthrower2 8y agoI read the Redux site for the first time recently and I realised that it is a transliteration of the Elm architecture (TEA). TEA is probably easier to understand first as it fits more nicely into its native Elm than Redux does into JS. I think Redux is quite simple conceptually, but if you just look at the code without the concept and reason behind it, it’ll look like complexity for the sake of it.
- manigandham 8y agoYou can use Mobx and get around all the manual effort of Redux.
- chrisweekly 8y agoIME, Mobx is much simpler than Redux. /$.02
- bfrydl 8y agoI don't think redux-thunk is the simplest solution. There's really no need to add anything to redux to support asynchronous code. You can just pass the dispatch function around. For example: async function getArticle(id, dispatch) { try { const res = await fetch(`/articles/${id}`); const text = await res.text(); dispatch({ type: 'GET_ARTICLE_SUCCESS', id, text }); } catch (err) { dispatch({ type: 'GET_ARTICLE_FAILURE', id, err }); } } In my opinion all this middleware business (thunk, saga, etc.) is trying to make redux do jobs it isn't supposed to be doing.
- acemarke 8y agoYes, it's true you can do that. However, it's not what we recommend. I specifically addressed the reasons why we recommend using middleware in the "Side Effects" section of my "Redux Fundamentals" workshop slides [0] [1]. The Redux FAQ entry on "Why do we need things like middleware for async behavior?" [2] also addresses this. In particular, I recommend reading Dan Abramov's answers on Stack Overflow on this top [3] [4] As always, it's up to you how you choose to write your code, but there's plenty of good reasons why middleware is our recommended approach. [0] https://blog.isquaredsoftware.com/2018/06/redux-fundamentals-workshop-slides/ https://blog.isquaredsoftware.com/2018/06/redux-fundamentals... [1] https://blog.isquaredsoftware.com/presentations/workshops/redux-fundamentals/side-effects.html#/4 https://blog.isquaredsoftware.com/presentations/workshops/re... [2] https://redux.js.org/faq/actions#how-can-i-represent-side-effects-such-as-ajax-calls-why-do-we-need-things-like-action-creators-thunks-and-middleware-to-do-async-behavior https://redux.js.org/faq/actions#how-can-i-represent-side-ef... [3] http://stackoverflow.com/questions/34570758/why-do-we-need-middleware-for-async-flow-in-redux http://stackoverflow.com/questions/34570758/why-do-we-need-m... [4] http://stackoverflow.com/questions/35411423/how-to-dispatch-a-redux-action-with-a-timeout/35415559 http://stackoverflow.com/questions/35411423/how-to-dispatch-...
- bfrydl 8y agoYes, I'm familiar with the arguments against it, but my experience using Redux has led me to strongly disagree with them. I don't think the proposed benefits have much value in actual practice, and limiting the use of dispatch to plain objects makes state logic easier to understand in my opinion. Also, I think my primary issue with redux-thunk isn't that you dispatch a non-object but that the getState argument encourages async operations which are dependent on the current store state, possibly its current state at multiple different points of time. Personally I think that as much as possible async operations should be written to use only parameters as input and dispatch actions as output. Plus I use TypeScript where things like this getState argument are really annoying for strong typing. You need to import the type of your store or store state in every file that uses a thunk. I also personally think that the extra ceremony applied to Redux is a contributor to the difficulty new developers have understanding it, because they believe that Redux does more than it actually does.
- m0meni 8y agoAFAIK concurrent React breaks a lot of the currently existing ecosystem. For example, I think right now the current versions of redux and MobX don’t work with it. Granted, concurrent mode is not even close to out yet, but I’m curious what the migration path looks like.
- Klathmon 8y agoI don't know the answer (or if there is a fully formed answer at this point), but I have heard the React team talk about this a bit. Facebook internally has a MASSIVE number of components, and apparently a lot of them are using older APIs and older paradigms. Because React is ultimately by and for Facebook, they simply can't afford to make lare breaking changes, it's just not a realistic option. Everything they do has to have a good mostly-automatable path forward. I don't know for sure how they will handle it, but I have a feeling it will be using the StrictMode stuff that they introduced a few versions ago. I'd wager they will have a way to enable concurrent react for a Component and the tree of children nodes, and will stick to the current implementation for everything that isn't compatible. This will let you enable the new features in only parts of your app that need it, or slowly migrate over to it and opt-in over time. And I believe I read somewhere that if a component runs happily in StrictMode that it's already concurrent-react ready (but please don't take that as fact!).
- acemarke 8y agoYeah, ConcurrentMode is going to be entirely opt-in, per subtree, as a component: `<ConcurrentMode>`. And yes, that's the point of `<StrictMode>`: a form of runtime linting for known patterns that will cause problems in CM.
- Tade0 8y agoImpressive, but I don't think there's much of a use case for this. Sure that last example ran at close to 60fps, according to the meter, but did it really? I mean, as a user I experienced no performance gains, because I was focused on that lower part of the UI and I think most users would as well.
- lilactown 8y agoI found the second example to be way less janky. I want to be able to see what I type as I type it (e.g. for spelling mistakes). Taking a second to correlate that with results I am willing to accept, but if an app is janky with basic interactions I am leaving.
- danabramov 8y agoI want to emphasise both of examples are intentionally janky (even though second is less so). As the article states, it literally has a for loop that doesn’t do anything to simulate an overly expensive tree (think thousand of DOM nodes). You can see the difference between first and second approaches that way. Although both would be fast if we remove that artificial slowdown (simulating a larger app). However I also want to note that you shouldn’t base your idea of what Concurrent Mode will feel like based on an alpha version demo. It’s work in progress and we didn’t mean to imply it’s ready to be denied at face value. https://twitter.com/dan_abramov/status/1103769293479653376 https://twitter.com/dan_abramov/status/1103769293479653376
- hombre_fatal 8y agoPeople are highly aware of when their input is locked up. It's like trying to type commands over SSH on a bad or laggy connection: you have to keep pausing, wait for it to catch up, and ensure there are no typos or anything. Oops, need to backspace, wait, and edit that character. Oops, backed up too far. Classic example of this is a naive markdown preview box that updates on every keypress. As the input grows, the experience becomes more intolerable until you're left typing the post in notepad and pasting it into the <textarea>. You are only able to look past it here because of the contrived example. Though I found the demonstration intolerable and would hope, as a user of your application, that you wouldn't settle on "meh, the user won't notice/care." Especially since you don't notice it on your developer workstation and I'm stuck using it from my low powered mobile device.
- gambler 8y agoYou can significantly improve on the baseline performance simply by doing: handleChange = event => { const value = event.target.value; this.setState({ inputValue: value }); setTimeout(() => { this.props.onChange(value); }, 1); setTimeout(() => { sendAnalyticsPing(value); }, 1); }; And wrapping mining function inside Name(): setTimeout(() => { miningBitcoin(2); }, 1); In fact, to me this pretty much seems as fast as their fancy solution. But what do I know, I'm just an idiot full-stack developer who doesn't use JS frameworks.
- acemarke 8y agoHow does this "improve" at all? In fact, that example will eliminate any chance React might have of batching multiple updates into a single render pass. React wraps all event handlers in a call to `unstable_batchedUpdates()`. All updates that are queued in that event handler will be batched together. Splitting updates into multiple ticks will keep them from being batched.
- gambler 8y agoTry it instead of theorizing: https://codesandbox.io/s/07293kpnn https://codesandbox.io/s/07293kpnn The UI is nearly as responsive as their improved example. I'm not a React expert, but I do know that browsers defer timeouts until they have time to process them. This can be used to take heavy-hitting functions out of events that block UI interactions. It can also be used for self-throttling recursive IIFEs.
- acemarke 8y agoAnd I would say I reasonably qualify as a "React expert", and was having a discussion on this topic yesterday: https://twitter.com/acemarke/status/1103373148169347072 https://twitter.com/acemarke/status/1103373148169347072 There's a lot of nuance involved here. Moving some behavior outside the current tick may speed certain things up. Keeping multiple React updates in the same tick may _also_ speed other things up. It depends on what work is being done in these additional callbacks, and where/when they're being executed. In this specific case: `this.props.onChange()` calls the parent component's `setState()`. That should ideally be kept in the same tick as `this.setState()`, so they can be batched. `sendAnalyticsPing()` does _not_ cause a React update. That should indeed be moved out to a separate tick, so that it doesn't slow down this update.
- dplgk 8y agoI understand the need but this adds serious complexity and wouldn't recommend that this becomes the standard for UX in React. A user is often ok with a delay and it may not worth the tech debt. That said, a very well written article.
- onion2k 8y agoA user is often ok with a delay... Every user group focus test I've ever done on an app with a janky UI has brought it up as a significant "The app is so slow!" issue. On the things I build users hate UI delays.
- taeric 8y agoThis is a tough one. If asked, most everyone will complain about delays. Just like, if asked, most people will complain about the color choice. Doesn't mean it is the best place to focus on at first. In areas where the latency has been solved, don't make the options worse for the user. There are bare minimums, but they are usually hard to mess up. Such that, if you are bringing something new to the table, focus on that first.
- philipp-spiess 8y agoKeep in mind that the APIs are still WIP. I choose an example with lots of APIs on purpose. There's a lot that can be inferred by e.g. looking at the event type or understanding semantics. I expect this to be better when the features near completion.
- danabramov 8y agoMost of the complexity is inside of React, not in the app. Your components look pretty much the same — except that you have more control over scheduling when you need to.
- dana321 8y agoReact trades simplicity of certain things such as dom manipulation, and makes it difficult to fetch external (ie noncompiled) html and include it as react dom nodes, and ad serving is pretty difficult too because most ads use document.write and this paradigm doesn't work with react, as well as single page applications and the rendering of contextual advertising requires server-side rendering too. State management solutions like redux; nobody i know or have seen does it exactly the same, its really tricky to use and takes a long time to get the hang of.
- akesablyan 8y agoI think this is a great point made. I wonder if it makes sense to build into the core of react to have render method execute on priority levels configured for the components themselves. I agree that this adds a good deal of complexity otherwise for quicker projects.
- philipp-spiess 8y agoSomething like this is definitely possible. For example a <div hidden> could apply all updates using a lower priority. This can be used to detect offscreen content or non-active tabs.
- danabramov 8y agoWhat complexity are you referring to? If you don’t use finer grained control then your React apps work exactly the same ways as they did before. The extra control is opt-in and you don’t have to use it.
- sktrdie 8y agoI feel that this low-level performance stuff should exist in browser-land and not in framework-land. Kudos to React for finding a good implementation though
- mpweiher 8y agoOr maybe not even in the browser but in the OS? It is interesting how we build a new layer on top, and then notice that we need to reproduce all the functionality of the lower levels. Maybe Open Implementation wasn't such a bad idea?
- pmdarrow 8y agoThe Chrome dev team is working to create a scheduling API in the browser: https://github.com/spanicker/main-thread-scheduling https://github.com/spanicker/main-thread-scheduling
- danabramov 8y agoYep, and React is actively collaborating with them.
- quickthrower2 8y agoWe’ll end up with threads in JS one day.
- danabramov 8y agoRelevant: https://github.com/facebook/react/issues/7942#issuecomment-254984862 https://github.com/facebook/react/issues/7942#issuecomment-2...
- amelius 8y agoHopefully without a "Global Interpreter Lock".
- dana321 8y agoI would prefer that they implement it in the same way go has with channels.
- DrFell 8y agoI think React is becoming a browser in a browser.
- XCSme 8y agoThis seems pretty nice! Personally, for most cases, I would just fix the actual problem instead (long-running tasks) by either moving them to a Worker, batching the work or using some LOD algorithm to only run to work for the needed granularity. This would improve the UX a lot and is not something that you have to do to often anyway.
- fovc 8y agoThe worker approach doesn't work if you need to update lots of Dom nodes. The example being a highlighter for a search term. While LOD would work (e.g., only update on screen names), the work featured to set that up is non trivial
- danabramov 8y agoThis might also add some context of why we’re not going with just workers (btw we tried that): https://github.com/facebook/react/issues/7942#issuecomment-254984862 https://github.com/facebook/react/issues/7942#issuecomment-2...
- deleted 8y ago[deleted]
- throwaway66666 8y agoWe used this technique in the IE6 days (with settimeout nonetheless). We had a very big list that was being filtered as the user typed, and we would perform 10 dom operations (they were all creating and appending elements to the dom), then timeout for 15ms, then 10 more operations, etc. If the user changed the text, we would clear the most recent timeout which would stop the chain, it was very clean actually. I suppose with requestAnimationFrame it's a bit nastier as you 'd need like a __dirtyRequestStop boolean check to break the scheduling, but probably much more elegant performance wise. The concept behind it, is that you give "air to the UI thread to breath". Basically instead of locking it for 100ms you lock it for less at the time, which is perceivable as just a delay, rather that the window completely freezing. Users would see the list progressively be created sometimes which was cool too, gave it a feeling of "this is doing some heavy work behind the scenes" without really doing much. documentFragment also was used for constructing the elements before appending the fragment to the main element :) I am wondering if that technique has any merit today, since it really helped back then. What is old will be new again :)
- underwater 8y agoIt's not a new technique. The innovation in React is allowing the framework to pause render on any component boundary, and detect and redo any stale renders when inputs change.
- danabramov 8y agoAnother important part is that’s React doesn’t commit partial results until the whole update is done. So you don’t see “half of an update”. That’s the benefit of doing it inside the library. We also reuse the same scheduling architecture for waiting for network and other IO. You can watch our latest talks on Concurrent Mode that touch on this here: https://reactjs.org/blog/2018/11/13/react-conf-recap.html https://reactjs.org/blog/2018/11/13/react-conf-recap.html
- acemarke 8y agoOh, it goes back quite a bit further than that :) https://blog.codinghorror.com/is-doevents-evil/ https://blog.codinghorror.com/is-doevents-evil/
- barbecue_sauce 8y agoIsn't this some of what Fiber was supposed to take care of?
- acemarke 8y ago"Fiber" was the codename for the internal rewrite that was completed and delivered as React 16.0. That rewrite has enabled all of the further functionality that's been implemented in 16.x, including the first stages of "Concurrent Mode".
- danabramov 8y agoDan from React team checking in, just wanted to post a few extra thoughts about this! https://twitter.com/dan_abramov/status/1103768273064259590 https://twitter.com/dan_abramov/status/1103768273064259590
- aidos 8y agoThis is really interesting work. Looking forward to seeing how this plays out. Someone below mentioned that it won’t play nicely with mobx - can you point to more details about the limitions that we will run into? Also just wanted to say a quick thank you to the whole React team for the work you’re doing. After some initial scepticism about the necessity of hooks, we’ve been really enjoying the mental model they bring to implementing more interesting behaviours in our components.
- nkg 8y agoAs users, don't you get mad when you type "mustang" in an input and it displays "msutgna" because of some badly handled onChange event? We are overriding so much of the browser's default behavior that we need to reimplement its basic features.
- svachalek 8y agoYes. I wish native browser inputs would step out of 1994, but at the same time my preferred answer to this case is simply using an uncontrolled input rather than piling more layers of complexity on top of it.
- symboltoproc 8y agoI've never experienced that. Mind sharing an example?
- bestest 8y agoThat would happen when, for example, you're saving the value of the text input in redux, and the input is then updated with that value on change, although it's also updated by the user typing and the thread is blocked at the same time, thus we have a race condition. That said — it only happens when one over-engineers stuff. Make sure to have a single source of truth, and that will be avoided.
- deleted 8y ago[deleted]
- philipp-spiess 8y agoThe best approach is to always updated the input synchronously in React (in the same tick when the event is handled). If you do it in another tick, you will always have to handle race conditions. This is a problem for all input elements though, not specific to React or even the Web.
- nkg 8y agoThe last time I experienced it I was using search bar on AliExpress.com's mobile website
- _zachs 8y agoThanks for the article! Well written and clearly explained Concurrent to me. Looking forward to trying out the API myself.
- tangym 8y agogreat article, thank you