P4.4: State and useState
While Props are read-only and passed from parent to child, State is a component's local memory. State allows components to store data that changes over time (like counter values, text input fields, or drawer toggles).
While Props are read-only and passed from parent to child, State is a component's local memory. State allows components to store data that changes over time (like counter values, text input fields, or drawer toggles).
Lesson: p4-4-state
While Props are read-only and passed from parent to child, State is a component's local memory. State allows components to store data that changes over time (like counter values, text input fields, or drawer toggles).
useState HookTo declare state inside a functional component, we use the useState Hook. Hooks are built-in React functions that let you connect with React's state engine.
import React, { useState } from 'react';
useStateWhen you call useState, it returns an array containing exactly two items:
const [count, setCount] = useState(0);
// ▲ ▲ ▲
// State Var Setter Fn Initial Value
Let's build a counter component that increments its value when a button is clicked.
import React, { useState } from 'react';
export default function Counter() {
// 1. Declare state variable initialized to 0
const [count, setCount] = useState(0);
// 2. Event handler function
const handleIncrement = () => {
setCount(count + 1);
};
return (
<div className="p-6 bg-slate-900 border border-slate-800 rounded-3xl text-center space-y-4">
<h2 className="text-xs font-black uppercase text-slate-450 tracking-wider">Interactive Counter</h2>
{/* 3. Display current state value */}
<div className="text-3xl font-black text-blue-400">{count}</div>
{/* 4. Bind trigger function to onClick */}
<button
onClick={handleIncrement}
className="px-4 py-2 bg-blue-600 hover:bg-blue-500 rounded-xl font-bold text-xs text-white transition-all cursor-pointer"
>
Increment Counter
</button>
</div>
);
}
[!IMPORTANT] State Updates are Asynchronous! Setting state does not immediately update the variable on the next line of code. Instead, React schedules the update and rebuilds the component with the new value.
const handleIncrement = () => {
setCount(count + 1);
console.log(count); // ❌ Prints OLD count value because update is scheduled!
};
Whenever a state variable changes via its setter function, React automatically invokes the component function again with the new state values, updating the browser DOM.