React ES6 Classes

🏷️ React ES6 Classes

ES6 introduced the class keyword, which is used in React to create class components. These components include features like:

βœ” State
βœ” Lifecycle methods
βœ” Methods (functions) inside the component


🧩 Basic Structure of a Class Component


 

export default App;

Key points:

  • A class component must extend React.Component

  • It must include a render() method

  • The render() method must return JSX


🧠 Using state in Class Components

Class components use state to store dynamic values.


 


πŸ” Updating State

State can be updated using setState() β€” never modify state directly.


 


🎭 Props in Class Components

Props are accessed using this.props.

Usage:

<Welcome name="Vipul" />

πŸ›  Binding this in Class Components

Sometimes event functions need binding because this() refers to the wrong context.

❌ Without Binding:

This can cause errors if the method is not bound.

βœ” Methods Automatically Bound Using Arrow Functions

This is the recommended ES6 way.


⏳ Lifecycle Methods (Important)

Class components have lifecycle hooks. Example:


 


Common Lifecycle Methods:

Method Purpose
constructor() Initialize state
render() Return UI
componentDidMount() Runs after component loads
componentDidUpdate() Runs after state or props change
componentWillUnmount() Cleanup before removing

πŸ†š Class vs Functional Components

Feature Class Component Functional Component
State Yes Yes (via Hooks)
Lifecycle Methods Yes Yes (via Hooks)
Simpler Syntax ❌ No βœ” Yes
Recommended Today ❌ Older βœ” Modern Approach

🎯 Summary

React ES6 Classes allow you to:

βœ” Create components using class syntax
βœ” Use state with this.state
βœ” Update state using setState()
βœ” Access props using this.props
βœ” Use lifecycle methods

You may also like...