Till now we have learned two ways of creating a component:
1. Using a javascript function that returns some JSX which represents the content rendered on the screen.
2. A class that extends React.Component implementing render method which returns the JSX expression that is displayed on the screen.
First one is called a Stateless component in that it can not maintain a state, it does not have access to the implicit state object provided by react.
Second one is called a Stateful component as it can access state object. Changes to the state object causes the changed portion of the state to be re-rendered. This means that if the state object contains an array of 5 persons which are being displayed on the screen and if we change the details of 3rd person, then the element that displays the 3rd person on the screen is re-rendered.

HeadStatelessStateful
SyntaxCreated as a function. Example,

function HelloComponent() { }

Created as a class that extends React.Component. Example,

class HelloComponent extends React.Component { }

State accessIt can not access state.It has access to the implicit state object that is present in React.Component class.
Lifecycle methodsA stateless component can not access Lifecycle methods.A stateful component can implement various lifecycle component methods provided by react.
Props and session access syntaxThis component can access props directly using props or the array supplied to it. Example,

function HelloComponent(props) {
   console.log(props.message);
}

Also, props array needs to be supplied as an argument to the component function.

Stateful component can access state and props using this. Example,

class HelloComponent extends React.Component {
   render() {
      console.log(this.props.message);
}
}

props array is implicitly available to the implementing class.

UsageThis component type should be preferably used when you do not need access to component lifecycle methods or state.This type of component should be used when it needs to manage state or access to lifecycle methods.

It is advisable to use stateless components as often as possible since if there are more stateful components, it becomes harder for the application to be managed. If there are many components that can change the state, it will be difficult to track which component changed the state.
But, if the component needs to have a state or tweak between component lifecycle, then go for stateful components.

0

Share your thoughts !!

Close Menu

Never Miss an article !

Get the new post delivered straight into your inbox, enter your email and hit the button

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

codippa will use the information you provide on this form to be in touch with you and to provide updates and marketing.