Skip to main content
React Introduction
CHAPTER 07 Beginner

React State Basics

Updated: May 13, 2026
20 min read

# React State Basics

1. Introduction

Props allow us to pass data downwards, but what if the data needs to change? What if a user types in an input field, clicks a "Like" button, or opens a dropdown menu? For data that changes over time and affects what the user sees, React uses State. In this chapter, we will introduce the concept of State, the heartbeat of interactive React applications.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Understand the difference between Props and State.
  • Understand why standard JavaScript variables don't update the UI.
  • Introduce the concept of Hooks (specifically useState).
  • Create interactive components that respond to user actions.

3. Beginner-Friendly Explanations

Props vs. State

  • Props are like parameters passed into a function. They are passed from the outside, and the component cannot change them. (Read-only).
  • State is like a local variable declared inside a function. It is managed internally by the component, and the component can change it.

Why not use regular variables?

If you declare let score = 0; in a component, and a user clicks a button that runs score = score + 1, the variable *does* update in memory. However, React does not know it updated. Therefore, React will not refresh the screen, and the user will still see "0". State is special because when a State variable changes, it tells React: *"Hey! My data changed. Please re-render this component so the screen shows the new data!"*

4. Introduction to useState

To use state in functional components, we use a special function provided by React called a Hook. The most important hook is useState. We will cover hooks deeply in later chapters, but for now, we will use it for basic interactivity.

5. Syntax Explanation

Step 1: Import useState

At the top of your file, you must import the hook from React.
jsx
1
import { useState } from 'react';

Step 2: Initialize State

Inside your component, you call useState(initialValue). It returns an array with two things:
  1. 1. The current value of the state.
  1. 2. A function used to update that value.

We use ES6 array destructuring to grab both: ```jsx id="ch7_ex1" // Example React component import { useState } from 'react';

function Counter() { // [currentValue, setterFunction] = useState(initialValue) const [count, setCount] = useState(0);

return ( <div> <p>You clicked {count} times</p> {/* When clicked, we call setCount with the new value */} <button onClick={() => setCount(count + 1)}> Click me </button> </div> ); }

1234567891011121314151617181920212223242526272829
## 6. Output Explanations
1. On the first render, `useState(0)` sets `count` to `0`. The screen says "You clicked 0 times".
2. The user clicks the button. `onClick` triggers the arrow function, which calls `setCount(0 + 1)`.
3. React sees that a state updater function (`setCount`) was called. It re-runs the `Counter` function.
4. On the second render, `useState(0)` remembers the new value. `count` is now `1`. The screen says "You clicked 1 times".

## 7. Real-World Examples
State is used everywhere in modern web apps:
- A boolean `[isOpen, setIsOpen]` for a dropdown menu.
- A string `[searchQuery, setSearchQuery]` for a search bar.
- An array `[cartItems, setCartItems]` for a shopping cart.
- A string `[theme, setTheme]` for a light/dark mode toggle.

## 8. Common Mistakes
- **Modifying State Directly:** NEVER do this: `count = count + 1`. This modifies the variable but bypasses React's update system, so the screen won't change. ALWAYS use the setter function: `setCount(count + 1)`.
- **Calling the setter function infinitely:** If you write `<button onClick={setCount(count + 1)}>` (without an arrow function), the code executes immediately when the component loads. This changes the state, causing a re-render, which executes the code again, causing an infinite loop that crashes the browser!

## 9. Best Practices
- Name your setter functions `set[VariableName]`. (e.g., `theme` and `setTheme`, `isPlaying` and `setIsPlaying`).
- Keep state as low in the component tree as possible. If only the `<Sidebar>` needs to know if it is open or closed, put the state inside `<Sidebar>`, not in `<App>`.

## 10. Exercises
1. Import `useState` in a new file.
2. Create a component with a state variable called `isOn` initialized to `false`.
3. Render a button that, when clicked, toggles `isOn` between `true` and `false`.

## 11. Mini Project: Interactive Counter App
Let's build a polished counter application with increment, decrement, and reset functionality.

jsx id="ch7_proj1" // Example React component import React, { useState } from 'react';

export default function CounterApp() { // Initialize state at 0 const [count, setCount] = useState(0);

return ( <div className="flex flex-col items-center justify-center min-h-screen bg-gray-100 font-sans"> <div className="bg-white p-10 rounded-2xl shadow-xl text-center"> <h1 className="text-gray-500 uppercase tracking-widest text-sm font-bold mb-4"> Current Count </h1> {/* Dynamic color based on positive/negative */} <div className={text-7xl font-black mb-8 ${count < 0 ? 'text-red-500' : 'text-blue-600'}}> {count} </div>

<div className="flex gap-4 justify-center"> {/* Decrement Button */} <button onClick={() => setCount(count - 1)} className="w-14 h-14 rounded-full bg-red-100 text-red-600 font-bold text-2xl hover:bg-red-200 transition" >

  • </button>

{/* Reset Button */} <button onClick={() => setCount(0)} className="px-6 h-14 rounded-full bg-gray-800 text-white font-bold hover:bg-gray-900 transition" > Reset </button>

{/* Increment Button */} <button onClick={() => setCount(count + 1)} className="w-14 h-14 rounded-full bg-blue-100 text-blue-600 font-bold text-2xl hover:bg-blue-200 transition" > + </button> </div> </div> </div> ); } ``

12. Coding Challenges

Challenge 1: Modify the counter app so that the count cannot go below zero. (Hint: update the
onClick for the decrement button to use an if statement or a ternary operator before calling setCount).

13. MCQs with Answers

Q1: What happens if you update a variable using
let val = 5; val = 6; instead of useState in React? A) React updates the UI instantly. B) The variable updates in memory, but the UI does not re-render. C) React throws an error. D) The variable is locked and cannot be changed. *Answer: B*

Q2: What two items are returned by the useState hook? A) The current state value and a function to update it. B) The previous state value and the new state value. C) A string and a boolean. D) The DOM node and its properties. *Answer: A*

14. Interview Questions

  • Q: Explain the difference between State and Props.
  • Q: Why shouldn't you modify state directly (e.g., this.state.name = "John")?

15. FAQs

Can a component have multiple pieces of state? Yes! You can call
useState as many times as you need. For example: const [age, setAge] = useState(20); const [name, setName] = useState("Alex");

16. Summary

State is the memory of a component. While Props are read-only data passed from above, State is mutable data managed from within. By using the
useState hook, you can track changes to variables, and React will automatically re-render the UI whenever that state changes.

17. Next Chapter Recommendation

In this chapter, we touched briefly on the
onClick` event to trigger our state updates. In Chapter 8: Event Handling in React, we will do a deep dive into user interactions, exploring clicks, form submissions, and keyboard inputs.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·