⚡ Lesson 3: State & Interactivity

Learn how useState makes your components interactive and reactive!

Welcome, Alex! 👋

This message is controlled by state. Try changing your name below!

🔢 Counter Demo

This counter started at: 0

0

✏️ Name Input Demo

Started with: "Alex"

Hello, Alex!(4 characters)

📱 Social Media Demo

@alex128 followers

Learning React state management! Started with 42 likes and 128 followers.

Stats

Likes gained:+0
Followers gained:+0
Engagement:33%

✅ Todo List Demo (Array State)

Learn React
Master useState

🎨 Theme Switcher (State Controls UI)

Current theme: blue (started with: blue)

🎯 What You're Experiencing

  • • Reactive updates: UI changes when state changes
  • • Initial values: Set starting state (try changing them!)
  • • Event handlers: Functions that update state
  • • Array state: Managing lists of items
  • • Conditional rendering: Show/hide based on state

⚛️ useState Concepts

  • • useState hook: Creates reactive state variables
  • • State updates: Re-render component when state changes
  • • Immutability: Always create new state, don't mutate
  • • Event handlers: Functions that respond to user actions
  • • Controlled components: Form inputs controlled by state

📝 How useState Works

1. Creating State

const [count, setCount] = useState(0);
const [name, setName] = useState("Alex");
const [todos, setTodos] = useState([...]);

useState returns [currentValue, setterFunction]. Initial value can be any type.

2. Updating State

// Simple update
setCount(count + 1);

// Update from input
setName(e.target.value);

// Update array (create new array)
setTodos([...todos, newTodo]);

Always use the setter function. For arrays/objects, create new ones instead of mutating.

3. State in JSX

{showWelcome && <div>Welcome, {name}!</div>}

<button onClick={() => setCount(count + 1)}>
  Count: {count}
</button>

State variables can be used directly in JSX. Changes trigger re-renders.

🚀 State Challenge!

  1. 1. Change initialCount to 100 and reload
  2. 2. Try different startingLikes and startingFollowers
  3. 3. Change initialTheme to "purple"
  4. 4. Set initialShowWelcome to false
  5. 5. Modify initialTodoText to something else
  6. 6. Play with all the interactive elements!