Chapter 5: State & useState Hook

1. What is State in React?

State is memory that a component can remember between renders. It’s the data that can change over time and when it changes → React automatically re-renders the component (and updates what you see on the screen).

Examples of state:

  • A counter that increases when you click a button
  • Whether a modal is open or closed
  • The text typed in a search box
  • The items in a shopping cart
  • Whether dark mode is on or off

Key points about state:

  • State is private to each component instance
  • Only the component itself can change its own state
  • When state changes → React re-renders the component (and its children)
  • State makes your UI dynamic and responsive

2. useState Hook – Basics

useState is the simplest and most common way to add state to a functional component.

tsx

Syntax:

tsx
  • stateVariable → the current value of the state
  • setStateVariable → the function to update the state
  • initialValue → the starting value (can be number, string, boolean, object, array…)

Important: Calling setStateVariable tells React to update the state and re-render the component with the new value.

3. Your First Counter Example (do this right now!)

Open src/App.tsx and replace everything with this:

tsx

What’s happening here?

  1. const [count, setCount] = useState(0); → We create state called count, starting at 0
  2. When you click +1 → setCount(count + 1) runs
  3. React updates count to the new value
  4. React re-renders the component
  5. The screen shows the new count value

4. Updating State Correctly (Very Important!)

Wrong way (common beginner mistake):

tsx

Correct ways:

Way 1 (most common):

tsx

Way 2 (safer when you depend on previous state – always recommended):

tsx

Why use the function form? If you do multiple updates in a row, React batches them. The function form guarantees you always get the latest value.

Example – multiple updates in one click:

tsx

5. Multiple State Variables (Realistic Example)

Let’s build a simple Todo form with multiple pieces of state.

Create src/components/TodoForm.tsx

tsx

Use it in App.tsx:

tsx

Summary – Chapter 5 Key Takeaways

  • State = memory that survives re-renders
  • useState = hook to add state to functional components
  • Always use function updater form (prev => …) when new state depends on previous
  • You can have multipleuseState calls in one component
  • Calling setState → triggers re-render with new state value
  • State is local to each component instance

Mini Homework:

  1. Create a component LikeButton with:
    • State: isLiked (boolean, starts false)
    • State: likeCount (number, starts 0)
    • Button that toggles like/unlike and increases/decreases count
  2. Bonus: Add a heart icon that changes color when liked (use emoji ❤️)

You may also like...

Leave a Reply

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