What are class-based Components in React?
Class-based components in React are an alternate technique to create reusable UI components using JavaScript classes. They are defined by extending React. Component class and implementing methods such as `render()` to define the component’s UI. Class-based components have their own state and lifecycle techniques.
Example: In this example, we’ve manipulated the state with the use of Class.
Javascript
//Counter.js import React, { Component } from 'react' ; class Counter extends Component { constructor(props) { super (props); this .state = { count: 0, }; } incrementCount() { this .setState({ count: this .state.count + 1, }); } render() { return ( <div> <h1>Count: { this .state.count}</h1> <button onClick={() => this .incrementCount()}> Increment </button> </div> ); } } export default Counter; |
Output:
Why to use React Hooks Instead of Classes in React JS ?
The introduction of React Hooks has changed the way we are managing states and lifecycle features. They offer more easy and functional way as compared to class based components. In this article, we will learn why to use React Hooks Instead of Classes in ReactJS, but lets first discuss about both React hooks and class based components.
Table of Content
- What are React Hooks?
- What are class-based Components in React?
- Advantages of Using Hooks over Classes
- Differences between React Hooks and Classes
- Conclusion