During my react coding review or discussion with the developers, Many put their questions about Class component vs Functional component use with real-life projects. eg. Where will we have to use class/functional components and why? Which is better in terms of performance or management?
Here, I am writing my experience for the above questions.
In react, we are having two types of components - Functional and Class Components. Both are having different rules, ways, and strengths. Nowadays, the React hooks had given powerful methods to functional components.
Currently, React Hooks are very famous to handle various tasks and manage the state in an easy way (useState, etc) like accessing state values from the parent, sharing values to child/parent components (useRef, forwardRef, useContext, etc), memory management, etc.
Additionally, We can manage the life cycle of a component using a hook (useEffect).
State Management: With Class components, we can easily manage the internal state values.
For beginners, It may create complexity (a little bit tricky) with the integration of state management libraries like Redux.
Life Cycle Management: Class components are very good with life cycle management (ComponentDidMount, ComponentWillMount, etc). It gives the power for managing life cycle stages. We can easily maintain our code with a life cycle function (attach or detach).
Functional components are stateless (without hooks) and class components are having state management. Before hook introduction with React, there was only one way to maintain state with components, which was class-based components.
Without hooks, a functional component is only a viewable component (JSX without any state or stateless component).
Hook functions (eg. useState) are having asynchronous behaviour and update state values asynchronously. Sometimes, It creates an issue with state handling/updating, failure state update on unmount of the component. To resolve these issues, we will have to put additional code or tricks or hacks with the functional component side.
Other hand with the class component, we manage these situations in a better way.
Conclusion: With Latest React, We can use both class or functional components for our development. I love the use of functional components (Easy to handle state, values, memory, data handling using hooks).
For complex or large state management / the common components/libraries/package development, I use the class components.
Which is your favourite?