React State Basics
# 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 declarelet 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 isuseState. 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.Step 2: Initialize State
Inside your component, you calluseState(initialValue). It returns an array with two things:
- 1. The current value of the state.
- 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> ); }
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.