When to use Class Component and Function Component??
Phani Murari
Posted on May 9, 2021
Hello Everyone,
In this post let's understand where to use the Class Component and Functional Component in react
Before diving, Let's start understanding what is a component in react?
Component
Websites or Web Applications developed using react is the combination and interlinking of different Components.
Components let you develop the UI of the website independently and even we can use reusable components to implement a similar UI.
React facilitates the developer with Class Component and Functional Components
Class Components
Class Components are built using ES6 Class
class Welcome extends React.Component {
render() {
return <h1>Super Excited to post my first post in Dev Community</h1>;
}
}
Functional Component
The simplest way to write the Component in react is to write a JavaScript function
function welcome(props) {
return <h1>Super Excited to post my first post in Dev Community</h1>;
}
We can use the Arrow Functions as well for the functional Components
const welcome = (props) => <h1>Super Excited to post my first post in Dev Community</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โs 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!
I'm Phani Murari
CodeIsPeace
Posted on May 9, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 28, 2024
November 27, 2024