4 ms·
Function components are a useful tool, but for the life of me I can't understand why the community currently builds everything with them. A lot of React code I
by PaulStatezny 4y ago
Function components are a useful tool, but for the life of me I can't understand why the community currently builds everything with them.
A lot of React code I run into these days would be simpler and less verbose with a traditional (non-function) React component.
- shadowgovt 4y agoMostly because functional components are understood to be the direction the framework is headed, with class components still supported for backwards compatibility reasons only. They'll almost certainly never go away without a major version bump because it would break way, way too many sites, but at some abstract level people feel class components will have a shorter shelf-life than functional. And certainly, any given third-party integration to React in the future is allowed to just say "We only support functional components" (with the corresponding hit to popularity, of course).
- PaulStatezny 4y agoThanks for commenting about the community sentiment. Interesting that you didn't comment at all about my take on functional components not being the best tool for every job in React. Curious – do you have an opinion?
- shadowgovt 4y agoIf I understand correctly, the team is pretty clear that if they had written React from scratch today, they would have gone with functional components and not class components. The major issue is life cycle. When is a class component instance created or destroyed? The answer is "whenever the framework feels like it," and that's a really ugly model for instance life cycle. Additionally and most importantly, it means that member variables on a React class component instance don't work the way that members are expected to work; you just can't rely on them having any particular value because the framework can create or destroy an instance when it feels like it for performance reasons. What good is a class and instance abstraction if when you try to use member variables (one of the key features of object-oriented programming) you're highly likely to just break the model in hard-to-debug ways? Because the framework isn't using class component instances like instances are supposed to be used, the React team is tossing that model to the curb.
- skydhash 4y agoIt's less code. And if you add hooks (for the reasons specified in the docs), you can have a smaller and more manageable codebase. But hooks differs so greatly from the easier to grasp lifecycle methods and state as component object's property that it's easy to have bugs if you do not grok it.