State is a built-in object in React used to store dynamic data in a component. Unlike props, state is local and can change over time.
State determines how the UI looks and behaves.
Why State Is Important
- Stores dynamic data like form inputs, counters, toggles
- Makes UI interactive
- Helps components re-render automatically when data changes
Using State in Functional Components
React provides the useState hook to manage state.
Example:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<h2>Count: {count}</h2>
<button onClick={() => setCount(count + 1)}>Increase</button>
</div>
);
}
Here:
count→ current statesetCount→ function to update stateuseState(0)→ initial value of 0
Using State in Class Components
class Counter extends React.Component {
constructor() {
super();
this.state = { count: 0 };
}
increment = () => {
this.setState({ count: this.state.count + 1 });
}
render() {
return (
<div>
<h2>Count: {this.state.count}</h2>
<button onClick={this.increment}>Increase</button>
</div>
);
}
}
State vs Props
| Feature | Props | State |
|---|---|---|
| Mutability | Immutable | Mutable |
| Component | Passed from parent | Managed within component |
| Usage | Data input | Dynamic data |
Best Practices
- Keep state minimal
- Don’t mutate state directly
- Use hooks in functional components
- Lift state up when needed for shared data
Conclusion
State is crucial for creating interactive and dynamic React apps. Learn it well, and your components will come alive.
Citations
https://savanka.com/category/learn/react/
https://www.w3schools.com/REACT/DEFAULT.ASP