When to use Class Component and Functional in React JS.
In React components are build to return JSX elements which are added to the root parent components from where they are initiated or called. This blog is an attempt to explain where to use Class component and Functional component in React JS.
Before all that, let’s recap what is a Component in React.
Component:
Components are independent and reusable bits of code. They serve the same purpose as JavaScript functions but work in isolation and return HTML. Components come in two types, Class components and Functional components.
Class Component:
A Class component is a more featured way to define a React component. It also acts like function that receives props as parameters, but that function also considers a private internal state as additional input that controls and returns JSX.
class Welcome extends React.Component{
render(){
return(
<h1>This is a Class Component</h1>
)
}
Functional Component:
A React functional component is a simple JavaScript function that accepts props and returns a React element. After the introduction of React Hooks, writing functional components has become the standard way of writing React components in modern applications.
function Welcome
return(
<h1>This is a Functional Component</h1>
)
}
Hope we had a short and good recap about the Class and Functional Components
The above two components which are written in class and Functional Components are equivalent from React point of view.
Now the major question rises in your developer’s mind!
When to use the Class Component and the Functional Component??
To answer this question, we need to have a decent understanding of the state of the component.
To recall or revise the concept of the state
of the component, I suggest you refer to this.
In class components, the render method will be called, whenever the state of the components changes. On the other hand, the Functional components render the UI based on the props.
Whenever we have the use case with the State of the component and rendering the UI based on the Component State, use the Class Components
Class Components should be preferred whenever we have the requirement with the state of the component.
In the beginner stage of the developer journey, we should be familiar with the Class Components and the Functional Components. As we progress towards the Advanced stage of our developer journey, we are able to understand much more cool stuff provided by React like Hooks
In React version > 16.8, React even facilitates developers with Hooks to use the state and other React features even without writing the Class Component
To know more about Hooks, Refer to this.
I love to appreciate your enthusiasm to learn more.
Thanks for Reading!