React - Preference: function class vs component class

假如想象 提交于 2021-01-15 18:47:45

问题


Are class components being abandoned?

I see that in several libraries examples have function components as a priority.

Especially React Navigation.

Likewise, React itself with Hooks only makes them available for function components.

The main question is: Why are function components being so prioritized?


回答1:


No, i think Class Components won't be abandoned today. Maybe in future.

They aren't lightweight as Functional Components can be, but i see a lot projects on community using Class Components.

However, here we have some reasons why the community is supporting the Functional Components approach:

  • Class Components requires more code but will also give you some benefits which you will see later on (the transpiled code by Babel will be larger too)
  • A functional component is just a plain JavaScript function which accepts props as an argument and returns a React element.
  • Functional component are much easier to read and test because they are plain JavaScript functions (less code).
  • The React team mentioned that there may be a performance boost for functional component in future React version

See this answer: https://stackoverflow.com/a/49613435/4119452

More: https://medium.com/@Zwenza/functional-vs-class-components-in-react-231e3fbd7108




回答2:


now a days, class components and functional components are almost same. In functional component Hooks were not introduced before and to make equivalent of class component, functional component gets new hooks like useState, useRef, useMemo which are equivalent to this.state, React.createRef and PureComponent.

Moreover, componentDidUpdate on class component can be used useEffect on functional component.

More details please check Functional Components vs Class Components in React and React JS — Understanding Functional & Class Components




回答3:


Hooks-first approach [Update 2020]

React team is currently re-building docs with Hooks-first approach which should be a preference for all new features and apps:

In future, is there any chance that Class Components becoming deprecated?

Class components are going to be around for years to come—for example, there are tens of thousands in production at Facebook already. However, we do recommend that new apps be built with function components and Hooks, which is why we want those docs front and center.

https://github.com/reactjs/reactjs.org/issues/3308



来源:https://stackoverflow.com/questions/61859809/react-preference-function-class-vs-component-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!