Ad

React Page Recommends Keeping Logic At A High Level

- 1 answer

I've read through quite a number of things recently trying to learn react and the best practices and I have repeatedly come across suggestions saying "try keeping your logic as high in the chain as possible".

I don't specifically understand why that is a suggestion. I understand that simplifies the code quite a bit, but I don't see how that would necessarily be good practice for projects that get large and complex. I also understand that the ideology behind react is "dom is slow javascript is fast", and that rewriting the shadow-DOM and 'diff'ing it makes re-rendering to the DOM quicker, but it just seems like a vast waste of computing time. When a project becomes more interact-able and more dynamic it seems like it would be recomputing something that could potentially be a long list, say 1,000+ items, and would waste cpu instead of just checking for ( add, move, remove, etc..) which would drastically reduce cpu.

Is there a reason behind Facebook's recommended algorithm approach?

Ad

Answer

I'm not sure the advice is necessarily aimed at people building extremely large and complex apps, per se, though it's not bad advice, and I personally still think it's a good idea to centralize state manipulation logic (e.g. flux or other similar "outside of React" patterns). I think the advice is aimed especially at people new to React to encourage them to develop a way of thinking about writing idiomatic React code:

  1. State from higher level components trickle into children via props.
  2. Lower level components affect data by calling callbacks passed via props.
  3. Embrace React's declarative programming model and let the virtual DOM take care of as much as possible.
  4. Don't have business-domain-related logic all throughout your component hierarchy; try to move it toward the top.
  5. Similarly, don't have business-domain-related state sprinkled throughout your component hierarchy; keep it toward the top (or, as I mentioned, outside of React entirely).

In my experience, following this advice works wonders for making a codebase easier to understand and amenable to change, especially as the codebase grows in size and complexity.

But like any other advice or "best practice," it doesn't mean you shouldn't analyze it critically. If you have a list of 1000 items and performance is becoming a concern, then of course move that logic into a better place, implement caching, or drop to a lower-level API. But I still think the advice is good in general — I'd only do those things if performance really was an issue. Too many people forget the rest of the quote:

We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%.

Ad
source: stackoverflow.com
Ad