



























Did you know that you could write any React Application as a single React Component? There's absolutely nothing technically stopping React from putting your entire application into one giant component. Your function would be HUGE. There'd be a TON of hooks for state and side-effects, but it's totally possible.
If you tried this though you'd face a few problems:
componentDidCatch to handle runtime errors. If you were allowed to use
react-error-boundary so you could use hooks, then it would be
considerably easier. But... I digress...css prop
anyway 😉).These are the reasons that we write custom components. It allows us to solve these problems.
I've had a question on my AMA for a while: Best ways/patterns to split app into components. And this is my answer: "When you experience one of the problems above, that's when you break your component into multiple smaller components. NOT BEFORE." Breaking a single component into multiple components is what's called "abstraction." Abstraction is awesome, but every abstraction comes with a cost, and you have to be aware of that cost and the benefits before you take the plunge
Duplication is far cheaper than the wrong abstraction. — Sandi Metz
So I don't mind if the JSX I return in my component function gets really long. Remember that JSX is just a bunch of JavaScript expressions using the declarative APIs given by components. Not a whole lot can go wrong with code like that and it's much easier to keep that code as it is than breaking out things into a bunch of smaller components and start Prop Drilling everywhere.
So feel free to break up your components into smaller ones, but don't be afraid of a growing component until you start experiencing real problems. It's WAY easier to maintain it until it needs to be broken up than maintain a pre-mature abstraction. Good luck!
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。