7. What is React State?

State is an internal data store for a component. Unlike Props (which are fixed), State is meant to change over time based on user interaction.

When the state changes, React "re-renders" the component to show the updated data on the screen automatically.

Real-world Examples:

8. React State Lifecycle

User Clicks Button

State Updates (setCount)

Component Re-renders

UI is Automatically Updated

Think of it as a continuous loop. The user acts, the data changes, and the view follows the data.

9. Rules of State

Rule 1: Private - State belongs only to the component it is defined in.

Rule 2: useState Hook - We use the useState hook to create state.

Rule 3: Never Mutate Directly - Always use the "Setter" function.

// ❌ WRONG
count = count + 1;

// ✅ CORRECT
setCount(count + 1);

Rule 4: Trigger - Updating state is the only way to tell React to refresh the screen.

10. React State Syntax

import { useState } from "react";

const [count, setCount] = useState(0);
PartMeaning
countThe Variable holding the current value
setCountThe Function used to change the value
useState(0)Starting value (Initial State)

11. Example: Counter App

import { useState } from "react";

function App() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <h1>Counter: {count}</h1>
      <button onClick={() => setCount(count + 1)}>
        Increase
      </button>
    </div>
  );
}

export default App;

14. Props vs State

FeaturePropsState
SourceFrom ParentInternal
EditableNo (Read-only)Yes
PurposeConfigurationInteractivity

15. State vs Variables

Standard JS variables (let x = 0) do not trigger a UI refresh. Only State triggers a re-render.

16. Example: Like Button

A "Like" button is a perfect state example. The number of likes is the state.

Initial Likes: 0

User clicks "Like"

setStatus(1)

UI shows "Likes: 1"

17. Practice Tasks

Task 1: Build a basic counter that increases.
Task 2: Add a "Decrease" button to the counter.
Task 3: Toggle text between "Hello" and "Goodbye".
Task 4: Toggle Login Status (Logged In / Out).

Advanced: Create a "Show/Hide" button that displays a secret message only when clicked.

18. Learning Flow

JSX → Props → State (Complete)

Next: Events → Hooks → API Integration

You are now a React Developer!