In this article we are going to discuss the class component in react. In SPFx (SharePoint framework), we use class components. Class components were the standard way to define components in React before hooks were introduced. To manage state and methods is a little bit different in class components rather than functional components. Further, we will dive into how we can manage state as well as methods. I will also discuss when to use the class component and why to use it.
What is a class component?
Class component is a javascript or Typescript class which extends React.Component base class. Class component must include the render() method to render UI. it includes JSX(JavaScript-XML).
import * as React from 'react';
class demo extends React.Component {
render() {
return <div>Hello, this is a demo class!</div>;
}
}
export default demo;
Now, we have seen the definition of class components and their structure.
State management in Class component
Now let's discuss state management in class component
Rather than using hooks to manage state in functional components, we can not use hooks directly in class components. In the class component, we update the state in different ways, like we manage the state by this.state and update via a method like this.setState({}).
import * as React from 'react';
class demo extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
incrementCounter = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
return (
<div>
<p>Counter: {this.state.count}</p>
<button onClick={this.incrementCounter}>Increment</button>
</div>;
)
}
}
export default demo;
Class components lifecycle methods
Now let us check out class components lifecycle methods.
Lifecycle methods help to control components' different behavior at different stages.
In the react class, components follow lifecycle methods, which can be categorized into three main phases. Let's discuss it.
Mounting
This phase includes methods like when the component is being created or its instances are inserted into the DOM.
- constructor(): used for initializing state and binding methods.
- static getDerivedStateFromProps(): this is called right before the component gets render. Both times on the initial mount as well as on the update.
- render(): this method must include a class component that returns JSX. In simple words, we can say that it renders UI.
- componentDidMount(): this method is called once after the component is rendered or mounted in the DOM. it does not call again and again, even if there are state or props updates.
Updating
This is the second phase of the component lifecycle which happens on change in props or state.
- static getDerivedStateFromProps(): works the same as in Mounting.
- shouldComponentUpdate(): control whether a component should re-render or not if there are state or props updates.
- render(): works the same as in Mounting.
- getSnapshotBeforUpdate(): which is used to get all information just before the component gets re-render or gets updated.
- componentDidUpdate(): this will call after the component gets updated and reflected in the DOM.
Unmounting
This is the last phase, where the component finishes its final updates and gets unmounted from the DOM.
- componentWillUnmount(): used for the cleanup, like removing event listeners, timers, etc. It is called just before the component gets removed from the DOM.
- Note: componentDidUnmount(): actually, there are no componentDidUnmount methods. It is only componentWillUnmount.
- Error Handling: componentDidcatch() and static getDerivedStateFromError(), which are useful for catch and error handling while the component renders.
export default class demo extends React.Component<> {
constructor(props) {
super(props);
this.state = { count: 0 };
}
componentDidMount() {
console.log('Component Mounted');
}
componentDidUpdate(prevProps, prevState) {
if (prevState.count !== this.state.count) {
console.log(`Count changed from ${prevState.count} to
${this.state.count}`);
console.log("componentDidUpdate")
}
}
componentWillUnmount() {
console.log('Component Will Unmount');
}
increase = () = > {
this.setState(prevState => ({count: prevState + 1}))
}
decrease = () = > {
this.setState(prevState => ({count: prevState - 1}))
}
render() {
return (
<div>
<p>{this.state.count}</p>
<button onClick={this.increase}>increase Data</button>
<button onClick={this.decrease}>decrease Data</button>
</div>
);
}
}
Props in Class component
Props are one kind of property that we use, like a mediator, which allows us to pass data from parent to child components. Below is an example of how we use props in class components.
class demo extends React.Component {
render() {
return <h1>Hello, {this.props.name}!</h1>;
}
}
export default demo;
// using that component by passing props as name
<demo name="user1"/>
As we have discussed above in class components, there are different ways to handle states and events or methods. So, let's look into how we can manage events or methods in class components and how we use them.
constructor(props: IDemoProps) {
super(props);
this.state = {
//state default values
};
this.demoEvent = this.demoEvent.bind(this);
}
As shown in the above code, we need to bind each event and method in the constructor.
Below is a complete example of event handling in the class component.
export default class demo extends React.Component {
constructor(props) {
super(props);
this.state = { message: 'Click the button' };
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState({ message: 'Button clicked!' });
}
render() {
return (
<div>
<p>{this.state.message}</p>
<button onClick={this.handleClick}>Click Me</button>
</div>
);
}
}
Now, let's talk about when to use class components and why.
In modern reactions, the first priority is a functional component, which includes the hook. Which makes it easier to handle state props and events. However, the react functional component uses the class component itself at the backend side. But you can use class components based on the below condition.
- If you are working on a legacy project that is older or not familiar with modern react with hook, then you must use the class component.
- In SharePoint, to date, it uses a class component, so if you are a SharePoint developer, then you have to use the class component. In fact, SharePoint provides a class component in its scaffold (initial code structure). After that, if you want to add your custom component, then you can use the functional component in it.
- If you want to utilize lifecycle methods or if you want more control over your component, then you can use class components.
Conclusion
in this article, we have seen the use of class components, which provide a structured way to update state and props to manage it. Also, we have seen how class components' lifecycle methods work efficiently to get more control over components and with essential responsibility of each method from the mounting to the unmounting phase. Also, we have seen how to manage or handle events and methods. Also discussed above when to use class components and why? with specific conditions.
FAQs
1. What is the difference between class and functional components in React?
Ans. Users are searching to understand the trade-offs between class-based and modern functional components using hooks.
2. How to manage state in React class components?
Ans. A very common query as hooks can't be used in class components, so people look for this.state and this.setState() usage examples.
3. What are lifecycle methods in React class components?
Ans. Lifecycle methods like componentDidMount() and componentWillUnmount() are still heavily searched, especially by developers maintaining older codebases or working with SPFx.
4. When should I use class components over functional components?
Ans. Developers are looking for valid scenarios where class components still make sense, such as in SPFx projects or legacy apps.
5. How to bind methods in React class components?
Ans. Handling this context in class components is a pain point, making this a frequently searched topic — especially around using .bind() in constructors.
6. What is unmounting in React class components?
Ans. Unmounting is the final phase of a component's lifecycle where it is removed from the DOM.
7. Which lifecycle method is used during unmounting in React class components?
Ans. componentWillUnmount() is called just before a component is unmounted and destroyed.