Building Your Learning Module...
Getting things ready for you!
Find videos you like?
Save to resource drawer for future reference!
Sometimes, a component needs to remember things. A counter needs to remember the current count. A form needs to remember what you've typed. A toggle needs to remember if it's on or off. This is where state comes in - it's like a component's personal memory!
Remember clicks, typing, scrolling, and other user actions
Track updates from API calls, timers, or real-time data
Manage loading states, error messages, and form validation
Show/hide elements, switch between views, and update styles
Component remembers: "The count is 0"
Component updates its memory: "The count is now 1"
Think of it like this: props are like parameters you pass to a function - they're read-only and come from a parent component. state is like a variable inside a function - the component owns it and can change it.
When you change state, React does something amazing: it re-renders the component. This means React runs the component function again, but this time with the new state value. The component updates what you see on screen automatically!
Component starts with initial state values
const [count, setCount] = useState(0)User interaction or event triggers state update
setCount(count + 1)React re-runs component with new state
Component() โ JSX with new countScreen reflects the new state visually
DOM updated โ User sees new countYou call the state setter function
React runs the component again
Screen shows the new state
Let's create a simple counter that remembers how many times it's been clicked. This example shows the fundamental pattern of using state in React components.
Forms are perfect examples of state in action. When you type in an input field, the component needs to remember what you've typed. This example shows how to create a controlled input using state.
This is a controlled component because React controls the input's value through state. The input's value is always equal to the state variable, making React the "single source of truth".