1. Props vs. State 🤔
So far, we've learned that **props** are passed *into* a component from its parent. A component cannot change its own props—they are read-only.
But what if a component needs to remember something that can change over time? For example, the current count in a counter, or the text in an input field. For this, we use **state**.
- Props are for data passed from a parent.
- State is for data that is managed *by the component itself*.
When a component's state changes, React will automatically re-render the component to reflect the new data. This is the key to making UIs interactive.
2. Introducing the `useState` Hook
In functional components, we add state by using a special function called a **hook**. The most important hook is `useState`.
To use it, you first need to import it from React. Then you call it inside your component to create a "state variable".
How `useState` works:
Calling `useState` does two things:
- It declares a state variable and gives you its current value.
- It gives you a special function to update that value.
We use "array destructuring" to get both of these in one line:
import { useState } from 'react'; // Or just React.useState
// Inside your component:
const [count, setCount] = useState(0);
- `count`: This is our state variable. Its initial value is `0` (the argument we passed to `useState`).
- `setCount`: This is the function we will call to update `count`.
3. Example: Building a Simple Counter
Let's build a component that uses `useState` to manage a counter. The component will display a number and a button. When the button is clicked, the number will increase.
const { useState } = React; // Destructuring from the global React object
function Counter() {
// 1. Create the state variable `count` and the `setCount` function
const [count, setCount] = useState(0);
// 2. Create a function to handle the button click
const increment = () => {
// 3. Use the setter function to update the state
setCount(count + 1);
};
return (
<div>
<p>Current count: {count}</p>
<button onClick={increment}>Click me</button>
</div>
);
}
// Render the Counter component
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Counter />);
- The component first renders with `count` as 0.
- When you click the button, the `increment` function is called.
- `setCount(count + 1)` tells React to update the state.
- React re-renders the `Counter` component with the new `count` value (1, then 2, and so on).