"If props are gifts from others, state is your own personal journal."
So you've learned about props in React—the way data comes into a component. Great! But now it's time to explore the flip side: state, where data lives and changes within a component itself.
This article will guide you through:
- What state is
- State vs props
- How to use
useState
- Real examples
- Common mistakes
- Tips and tricks
- Even a todo list demo!
What is State?
State is how a React component keeps track of changing data over time.
If props are like packages you receive, state is your private stash of notes.
Example:
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click Me</button>
</div>
);
}
Explanation:
useState(0)
creates a state variable starting at 0count
holds the valuesetCount
updates it
Props vs State
Props | State |
---|---|
Passed from parent | Managed by the component itself |
Immutable | Mutable with setState |
Controlled externally | Internal behavior |
More useState Examples
1. Controlled Input
function Form() {
const [input, setInput] = useState("");
return <input value={input} onChange={e => setInput(e.target.value)} />;
}
2. Toggle Component
function Toggle() {
const [isVisible, setIsVisible] = useState(true);
return (
<>
<button onClick={() => setIsVisible(!isVisible)}>
{isVisible ? "Hide" : "Show"}
</button>
{isVisible && <p>You can see me!</p>}
</>
);
}
3. Theme Switcher
function ThemeSwitcher() {
const [theme, setTheme] = useState("light");
return (
<div className={theme}>
<button onClick={() => setTheme(theme === "light" ? "dark" : "light")}>
Switch to {theme === "light" ? "Dark" : "Light"} Mode
</button>
</div>
);
}
Tips for Using State
- Never modify state directly. Always use the setter!
- Use callbacks if updating based on previous state:
setCount(prev => prev + 1)
- Break big state into smaller ones for clarity
Common Pitfalls
- Trying to mutate state directly
- Expecting immediate state updates (they're async!)
- Overusing state for derived data from props
Build a Todo List
function TodoApp() {
const [tasks, setTasks] = useState([]);
const [input, setInput] = useState("");
const addTask = () => {
if (input) {
setTasks([...tasks, input]);
setInput("");
}
};
return (
<>
<input value={input} onChange={e => setInput(e.target.value)} />
<button onClick={addTask}>Add Task</button>
<ul>
{tasks.map((task, index) => <li key={index}>{task}</li>)}
</ul>
</>
);
}
Using useEffect with useState
import { useState, useEffect } from "react";
function Timer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setSeconds(prev => prev + 1);
}, 1000);
return () => clearInterval(interval);
}, []);
return <p>Time: {seconds}s</p>;
}
State is a cornerstone of interactivity in React. It stores what changes and determines what the UI shows. Whether it's a counter, form, or real-time app, state is the muscle behind your UI.
"Treat state like your component's brain. Keep it smart and tidy."
0 Comments:
Post a Comment