简体   繁体   中英

React - Are class components ever used?

I'm going through some courses that were made before react hooks were a thing, now I'm wondering if there is any reason at all to use class-based components over functional components now that hooks exist?

I can't seem to come up with a reason or scenario where a class-based component would be preferable, but maybe I'm just not aware of certain corner-cases where a class-based component would be the go-to choice.

Appreciate any feedback regarding this.

Thanks in advance!

Class components are still used, but there is no particular reason to continue to do so. Tthe Facebook team recommends that all new React code is hook-based functional components, and not class-based. You can mix class components and hook-based components, so there is no reason to rewrite your class components.

You can read more at https://reactjs.org/docs/hooks-faq.html

At the company I work for we have mixture of both since we started using react before hooks. In my experience class components tend to have a lot more state logic, are fatter, tightly coupled, and harder to test. However, even though we're moving towards developing functional components, some people coming from ac# background tend to pick up class based components more easily. I would highly suggest using functional components but depending on the background of your team it might not hurt in the short run to use class based ones.

The only good reason that I can think of for using class components these days would be to create error boundaries as:

Only class components can be error boundaries.

From https://reactjs.org/docs/error-boundaries.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM