React State β€” Explained in Detail

Subject: React

🧩 What is State in React?

In React, state is an object that stores dynamic data for a component. When the state changes, React automatically re-renders the component to reflect the new data in the UI.

Think of state as the brain of your component β€” it remembers information over time and reacts to user input or events.


πŸ” Props vs State

PropsState
Passed from parent to childStored inside a component
Read-onlyMutable (can change over time)
Makes components reusableMakes components interactive

βœ… Using State in Functional Components

React uses a special Hook called useState() to manage state in functional components.

πŸ”§ Syntax:

  • state: the current value
  • setState: function used to update the value
  • initialValue: initial value (number, string, array, object, etc.)

πŸ§ͺ Example: Counter App

🧾 Output:


βœ… Using State in Class Components (Legacy)


🧠 Why is State Important?

  • Enables interactive components
  • Makes UI dynamic and responsive
  • Triggers automatic re-rendering on update

πŸ” Updating State Correctly

❌ Wrong:

βœ… Right:

If new state depends on old state:


🧰 Multiple State Variables

Or use an object:


🧠 Best Practices

TipWhy?
Use separate states for unrelated valuesImproves clarity and avoids bugs
Never modify state directlyReact won’t detect changes otherwise
Use functional updates when neededAvoid stale values
Keep state minimalStore only what’s necessary

πŸ“Œ Summary

ConceptDescription
StateData that determines component behavior
useState HookDeclares state in functional components
setStateUpdates state and re-renders component
Class StateUses this.state and this.setState()

πŸ”š Final Words

State makes components dynamic.

It's a core concept for building interactive UIs.

Managed differently in functional and class components.

πŸ‘‰ Check the State Cheat Sheet