State in React.js with Examples
State in React.js with Examples
State is a built-in object in React
that allows components to store and manage data that can change over time.
Unlike props, which are immutable, state is mutable and can be updated using
the setState method (in class components) or useState hook (in functional components).
1. State in Functional Components (Using Hooks - useState)
Since
React 16.8, functional components can use state with the useState hook.
import React, { useState } from "react";
Explanation:
- useState(0) initializes the state
variable count with 0.
- setCount updates the state when the
buttons are clicked.
- The component re-renders
when the state changes.
2. State in Class Components (this.state)
In class
components, state is managed using this.state and
updated using this.setState().
Explanation:
- this.state = { count: 0 } initializes the state.
- this.setState({ count:
this.state.count + 1 }) updates the state and re-renders the
component.
- Methods increment and decrement modify the state when
buttons are clicked.
Key Differences Between State in Functional and
Class Components
|
Feature |
Functional Component (useState) |
Class Component (this.state) |
|
Syntax |
const [state, setState] =
useState(initialValue); |
this.state = { key: value }; |
|
State
Updates |
Uses setState(value) |
Uses this.setState({ key: value }) |
|
Simplicity |
More
concise and readable |
More
verbose |
|
Performance |
Preferred
in modern React (lightweight) |
Uses this binding, slightly less
efficient |
Conclusion
- Use Functional Components (useState) for modern React
applications.
- Use Class Components (this.state) when working with legacy
code.
- The useState hook is simpler and
preferred for handling state in functional components.
Comments
Post a Comment