11 ms·
We memo all the things (2020)
- have_faith 5y agoIt certainly feels like a failing of the hooks design that these subjects are so common (I love hooks generally!). When someone introduces a new paradigm that by design has a list of footguns to avoid you can't help but wonder if this was necessary. Has anyone tried tackling a hooks-like api that fixes the known pitfalls? encapsulating shared logic with hooks is a massive benefit but the subtleties can be difficult to teach to others.
- jamespwilliams 5y agoKind of makes you wonder why React.memo isn't just the default behaviour. https://github.com/facebook/react/issues/14463#issuecomment-673844197 https://github.com/facebook/react/issues/14463#issuecomment-... suggests it was meant to be the default behaviour, but was scrapped because it would "break backwards compatibility". No source is given for that claim though.
- baxuz 5y agohttps://overreacted.io/before-you-memo/ https://overreacted.io/before-you-memo/ https://blog.isquaredsoftware.com/2020/05/blogged-answers-a-mostly-complete-guide-to-react-rendering-behavior/#memoize-everything https://blog.isquaredsoftware.com/2020/05/blogged-answers-a-...
- nop_slide 5y agoInteresting, I mostly followed this approach which is to basically never use those constructs unless you are 100% certain you know what will happen. https://kentcdodds.com/blog/usememo-and-usecallback https://kentcdodds.com/blog/usememo-and-usecallback TLDR; > Specifically the cost for useCallback and useMemo are that you make the code more complex for your co-workers, you could make a mistake in the dependencies array, and you're potentially making performance worse by invoking the built-in hooks and preventing dependencies and memoized values from being garbage collected. Those are all fine costs to incur if you get the performance benefits necessary, but it's best to measure first.
- antihero 5y ago> you could make a mistake in the dependencies array, This is an auto-fix with eslint, and when it isn't exactly right (you need a "one way update") you can override that rule. I would posit that passing a value that is regenerated every render (as opposed to when it actually changes) outside of the component (via props or context) is much more dangerous and likely to create infinite loops. For stuff that stays internal, sure, knock yourself out (until it is required by a useEffect or anything else that needs dependencies).
- jakelazaroff 5y agoThe problem with avoiding useCallback is that another hook will bite you: useEffect. If you need to define functions that interact with your component's state, you have to memoize them with useCallback (or useRef) to avoid a useEffect infinite loop. What's even worse is that if functions passed as props are unstable, your useEffect will run every time the parent component renders — meaning that a component can't trust functions passed into it. This is one of many reasons I think useEffect is a huge footgun, and I really wish we had a better primitive for causing side effects.
- antihero 5y agoI wouldn't say useEffect is a footgun, it just requires realising that React is doing shallow comparisons.
- nfRfqX5n 5y agovery good point
- jakelazaroff 5y agoTo me, a footgun isn't necessarily something that is hard to understand, but also something that's easy to misuse even if you understand it.
- deckard1 5y agohooks in general are a huge footgun. You need to place them at the preamble of your function (and not nested). They have to be named with "use" prefix (worth mentioning is React basically commandeered the entire "use" namespace for their own purposes via lint enforcement, which will bite you in the ass eventually), and they are poorly designed. Take useRef for example. You'd logically expect it to work with useEffect and that would be how you use refs in hooks land. But of course, refs are still a design wart on React (they've been through, what, 4 iterations now and they still can't figure out the interface?!). So of course you need to use useCallback. So what is the point of useRef then? I have no idea. The only use I've found is for "instance" variables. Or maybe onClick callbacks that run later. But now you have a ref that only works in some cases and not others. Yay, "composability" Browse the React docs and you'll find the caveat-to-design ratio is exceedingly high. On any other project you'd assume this is beta or alpha ware.
- jasonkillian 5y agoThis is a great article and I agree with it fully. The argument that a lot of popular React voices have made, "React is fast and it's prematurely optimizing to worry about memoizing things until a profile shows you need it", has never rung true with me. First and foremost, there's a huge time cost to figuring out what those exact spots that need optimization are, and there's also an educational cost with teaching less experienced engineers how to correctly identify and reason about those locations. There are only two reasonable arguments for not using `memo`, `useMemo`, and `useCallback`. The first is that it decreases devx and makes the code less readable. This one is true, but it's a very small cost to pay and clearly not the most important thing at stake as it's only a slight net effect. The second argument is that the runtime cost of using these constructs is too high. As far as I can tell, nobody has ever done a profile showing that the runtime cost is significant at all, and the burden of proof lies with those claiming the runtime overhead is significant because it doesn't appear that it is typically when profiling an app. So, given that the two possible reasons for avoiding `memo`, `useMemo`, and `useCallback` are not convincing, and the possible downsides for not using them are fairly large, I find it best to recommend to engineering teams to just use them consistently everywhere by default.
- Zababa 5y agoI've always thought of "premature optimisation" as optimising something that's not your "hot path". If there's no clear hot path, everything is the hot path, and small optimisation gains everywhere are the only thing you're going to get. So at this point, it's not premature. You could also rewrite your code so that there is a clear hot path, but in that case it seems to be React rendering, that's optimised by using memo and avoiding it completely.
- wpietri 5y agoHow could you not have a hot path? You're saying that you've measured actual usage and discovered that each thing happens to be called exactly the same number of times? That strikes me as extraordinarily improbable.
- 5y ago
- eatonphil 5y agoI like React a lot and have used it professionally for more than 5 years. First off I mostly haven't needed to memoize any time I can remember in any enterprise (non-SaaS) production or personal apps. But surely CoinBase is at a bigger scale than my apps were/are. But if it's the case that memoizing is such a good thing to do despite the effort (and I'm not debating that in this question), why is React designed in a way that requires you to opt into it and write the same boilerplate all over the place? If hooks make this a problem maybe hooks aren't the best (or at least pinnacle) design? (And I really prefer hooks, personally.)
- marcellus23 5y agoyeah, I was thinking about this too as someone who's not super familiar with React — why isn't memoing the default behavior?
- Zababa 5y agoI think that's because everyone needs to debug their React app, but not everyone needs the performance. So you optimise for the most common use case, where you make debugging easier. Memoization is a form of caching, caching is hard. Most backend web frameworks don't come with a cache by default, you add one when you need the performance. It's the same here.
- nfRfqX5n 5y agothe only time I find it to be required is when passing in callbacks to custom hooks with props that may change and you'll notice immediately because the callback will continuously run
- jdjb 5y agoIf you're using React.useCallback to avoid triggering further hooks down the line, then you're using it wrong. Since React.useCallback is ostensibly just React.useMemo wrapped around a function, this note in the documentation is just as applicable: You may rely on useMemo as a performance optimization, not as a semantic guarantee. In the future, React may choose to “forget” some previously memoized values and recalculate them on next render, e.g. to free memory for offscreen components. Write your code so that it still works without useMemo — and then add it to optimize performance.
- jon-wood 5y agoThis feels to me like another example of how the drive to use nothing but functional components in React is harming readability. Class based components were allowed to define a `shouldComponentUpdate` method which would be called ahead of rendering to decide whether a re-render is needed. Having the parent component memoise the component instead feels like a step backwards as we're now asking the parent to carry an understanding of a child component's implementation to decide whether re-renders are needed, rather than allowing the child to communicate that up the tree.
- beaconstudios 5y agothe parent doesn't have to memoise the component though. You can do this: export default React.memo(function myComponent(props) { // implementation }); though you would likely want to set displayName before exporting, in reality.
- jon-wood 5y agoIn which case, I stand corrected. I’ve not used React for a while and wasn’t aware that was possible.
- FalconSensei 5y agoBut that is still memo-ing, just in a different part of the code. And I'm not sure wrapping all components in React.memo is a good practice, otherwise all components would be memo-ed by default. `shouldComponentUpdate` is more explicit
- ramesh31 5y agoHave you ever dug through a complex heavily nested application trying to debug a performance issue, only to find a custom shouldComponentUpdate method within every individual component? It makes debugging an absolute nightmare.
- psadri 5y agoWhat is your proposed alternative?
- nathias 5y agoThis is an antipattern for a reason. Not only is the code less readable, it builds bad habits of code splitting state management and overall structure. A much better alternative is to just learn to understand the tools you are using better.
- d23 5y agoI have basically no interest in frontend stuff, but I can't stop staring at this page. I think it's the overall color scheme and that body font. It's gorgeous.
- Zababa 5y agoThere's no mention of what I think is the most important point: how is this enforced? If that's with a tool, I think it's great and a sane way to do things. If it's by asking everyone to remember doing it, I think it's a missed opportunity. It's also interesting to see the age-old functional programming problem: you trade performance for ease of development. I think these days people assume that things like immutable data structures are optimised under the hood. That doesn't seem to be the case with React, as you have to explicitly use a performance trick everywhere. Their argument that it would be premature optimisation to think about where memo is not needed makes sense, it's an interesting shift of optimisation of the runtime performance vs optimisation of the dev time. > Using memo and its cousins everywhere is a sane default. It’s like a mask mandate during a coronavirus pandemic. Sure, we could have everybody tested every day and only ask people who are actively contagious to wear a mask. But it’s far cheaper, simpler, and ultimately more effective to ask everybody to wear a mask by default. That's a good metaphor. It's easier for the people who decide, by shifting the burden on everyone else. I personally get headaches by wearing a mask all the time at work. I think I may get headaches too if I had to remember something like this all the time.
- nfRfqX5n 5y agoI think it would be easy to create a rule to see if the default export is wrapped in memo, but you could also just have it as a coding standard
- BinaryBullet 5y agoI wonder if this is the plugin they are using: https://github.com/steadicat/eslint-plugin-react-memo https://github.com/steadicat/eslint-plugin-react-memo Does anyone know of any other eslint plugins that help enforce this?
- fabiendem 5y agoThe author of the article wrote the ESLint plugin: https://github.com/steadicat https://github.com/steadicat So they probably use(d) it.
- senand 5y agoThis should have „React:“ mentioned in the title. I was thinking about a technique to write things down…
- lawwantsin17 5y agoI like that in the end he compared React to a virus that's ruining lives and it's solution to a universal mandate. I've got one for you. Don't use React with static content.
- kecupochren 5y agoI find the state of things in React, pun intended, a bit sad. Hooks are definitely an improvement over class based components but it still suffers from the same issue - having logic and state in the view layer leads to spaghetti code. Not to mention dependency arrays which are easy to get wrong and the weird syntax you end up with everywhere. I'm a big fan of MobX and it pains me to no end that it didn't took off better. It's a godsend from like 5 years ago and it makes so many of these React pain points disappear. Instead of adding state to your components here and there, it works outside of the view layer. You define the model, derived computed views, actions and then just use it inside your components. You never ever worry about performance because MobX knows what is used where and it will optimize your renders automatically. Moreover, dealing with state outside of the view layer makes it much more easier to refactor, reason about and test your app. Sure, you can do the same with Redux but it's 10x more code. I recommend this article on this topic by the author - https://michel.codes/blogs/ui-as-an-afterthought https://michel.codes/blogs/ui-as-an-afterthought
- brundolf 5y agoI +1 MobX wherever I see it mentioned, but I have to disagree here: > having logic and state in the view layer leads to spaghetti code Sometimes it makes sense to put logic and state in your view components, and the wonderful thing about MobX is that it doesn't care. It lets you freely move your state around to wherever you want it to live: inside components, outside components, in a module-scoped object, in a global store, all of the above. It's just JavaScript objects. For those fighting with hooks: one of the best things about MobX is that it does all dependency-tracking (for effects, but also for components) automatically and flawlessly. An entire problem-space that's usually easy to mess up just vanishes in front of your eyes. Going back to anything else feels like going back to the dark ages.
- morgancmartin 5y agoI'm not familiar with MobX, but I am a big fan of Jotai (https://jotai.pmnd.rs/ https://jotai.pmnd.rs/). It is a spiritual offshoot of Facebook's experimental(?) Recoil library. It is a bottom up approach to state. Everything is modeled as atoms. Atoms can be defined in any module and are accessed by simply exporting/importing from/to the module. Simply call the useAtom hook and you're now using that state atom. Under the covers it is scoped via a top-level React context, I believe. Atom derivation, read/write, async, it's all there. It also hooks into a lot of other popular state libs like redux, XState, Zustand and many others. I much prefer it to Redux because there is zero boilerplate and extremely flexible. It can be easy to hang yourself with all the extra rope it gives you if you aren't careful though.
- ald890 5y agoI created the benchmark for this. Because in every aspect it seems that React.memo is better. Especially when we are sure of stable argument references. Even when you add children to the component with memo, the worst case performance will be the same. https://codesandbox.io/s/react-memo-benchmark-m2bk6?file=/src/App.js https://codesandbox.io/s/react-memo-benchmark-m2bk6?file=/sr...
- meowtimemania 5y agoHas anyone added a compilation step that adds all the memoization boilerplate for you?
- hyzyla 5y agoI think it can be a solution to readability problem
- andkon 5y agoDumb question, but is there an equivalent concern for Vue? Or a reason why this kinda checking isn't necessary there?
- vlunkr 5y ago> If you’ve ever profiled a React app – even in production mode – you know there is a non-negligible performance impact to every component that renders. Maybe it's just me, but I've used React for ~5 years and I've never needed to profile an app, since the performance out of the box has always been good enough.
- jbaudanza 5y agoThe situation is much more severe with react-native, which doesn’t have a JIT compiler available.
- steve_adams_86 5y agoI don’t disagree that this likely improves performance in most cases, and I don’t blame the author here for any of my concerns. We’ve implemented this in our code base and it’s awful. Yes it improves performance. It also makes debugging terrible. Combined with contexts, the react dev tools are virtually useless anywhere below a context with a memoized value. Profiling is harder because of frameworky misdirections as well. You can do coarse benchmarks but actually following code in a profile gets noticeably worse once you memo everything. I hope this is fixed. I really enjoy react, but this odd thing about it - that we arguably should memoize everything manually, and that it does make the dev tools a mess, is a huge hit to developer experience. So tired of “Component did not render” in the Component tab.
- Arch-TK 5y agoThis was in 2020. I assume the team got made redundant in the last year or something. Coinbase has genuinely been the slowest performing website I've used in the past couple of years.
- fabiendem 5y agoI asked the author on Twitter if this approach was still in place, but didn't get a reply :/
- fabiendem 5y agoEdit: He did reply: https://twitter.com/steadicat/status/1452686612370915328 https://twitter.com/steadicat/status/1452686612370915328
- steadicat 5y agoThe team actually became part of a company-wide effort called Client Foundations! And no, we haven't changed our mind on this. (BTW we're hiring. :))
- cheeew 5y agoI've normally heeded to the advice from Dan Abramov (https://overreacted.io/before-you-memo/ https://overreacted.io/before-you-memo/) and KCD (https://kentcdodds.com/blog/usememo-and-usecallback https://kentcdodds.com/blog/usememo-and-usecallback): mainly due to the fact that I figured performance would take a significant hit by using unnecessary React.memo / useMemo calls throughout the codebase. One negative side-effect I could see as a result of this pattern is devs becoming too reliant on these optimizations and neglecting composition. But I suppose if the performance gain is substantial enough and DX isn't negatively impacted too much, it could serve as worthwhile-- especially at the level of scale which Coinbase requires.
- jbaudanza 5y agoFrom the useMemo docs: https://reactjs.org/docs/hooks-reference.html#usememo https://reactjs.org/docs/hooks-reference.html#usememo You may rely on useMemo as a performance optimization, not as a semantic guarantee. In the future, React may choose to “forget” some previously memoized values and recalculate them on next render, e.g. to free memory for offscreen components. Write your code so that it still works without useMemo — and then add it to optimize performance. I think about this section a lot. If they actually changed useMemo to sometimes "forget" values, it would break so many useEffect dependency arrays (including my own).