Recently an interviewer asked me about choosing between a functional component and class component. Why do I write functional component instead of a class component? Great question.
I, someone who just learned React with React Hooks at the same time, obviously, had no idea. It seems to me that both can do the same thing. I don't know the pros and cons of choosing between the two, besides the obvious better readability and easier to debug, 1-0 for functional component. The choice for me was always functional component, I should have questioned more. Did React Hooks just came out much later than React, so that senior developers have been using class because functional components are very limited? And now that React Hooks came out to offer to fix all its functional component limitations? - I don't know... really you have to ask those Facebook React genius developers.
About the class components vs functional components, it was recommended that it's better to use functional over a class component, they have better readability and easier to debug, etc. Before React Hooks, I guessed class was the only way to have state inside a component. React main page shows that the React Hooks let us use functional components without the need to use class. And it looked like React Hooks allow functional components to use state, and many more things, which was the main reason as why we use class over functional components. But is really only offer good things without side effects?
Any senior developer advice are very welcomed !!
John Carmack. Oculus VR CTO:
"Sometimes, the elegant implementation is just a function. Not a method. Not a class. Not a framework. Just a function."
Top comments (1)
Hi Ngan, you would use a class-based component when you need the component to manage its own local state, or if you need the component to utilize lifecycle methods. Technically yes, hooks do allow you maintain local state in a functional component, functional components are declarative style while classes are OOP style.
Most enterprise-based React apps are built with class-based components and they are particularly interested in refactoring their apps to be purely functional components, I still think class-based will be the dominating paradigm going forward because it helps distinguish between between which components are stateful components (class-based) and which are just passed state as a container (functional).