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
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:
π 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
