What do you mean by State in React? See Example

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 state
  • setCount → function to update state
  • useState(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

FeaturePropsState
MutabilityImmutableMutable
ComponentPassed from parentManaged within component
UsageData inputDynamic 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

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *