22. State (useState)
Making the UI Dynamic
Props are static. Once a component receives props, it cannot change them. But what if a user clicks a "Like" button and the count needs to go from 0 to 1? Or what if a user types in a search bar? For data that changes over time, we use State.
The useState Hook
To add state to a functional component, we import the useState hook from React. A "Hook" is simply a special function that lets you "hook into" React's internal features.
Why Use the Setter Function?
You might wonder why you can't just write count = count + 1. You must never mutate state directly. React monitors the UI. If you bypass the setter function (setCount), React will not know the data changed, and the screen will not update. Calling the setter function explicitly tells React: "Hey, data changed, please re-render the screen."
State Updates are Asynchronous
When you call a setter function, React doesn't update the variable instantly. It schedules an update for the next render. If you need to update state based on its previous state (like a counter), you should pass a function into the setter.
State is Isolated
State is local to the specific instance of the component. If you render the <LikeButton /> three separate times on the page, each button has its own completely independent count state. Clicking one will not affect the others.
Knowledge Check
Ready to test your understanding of 22. State (useState)?