Skills / Front-end apps with React / Props and state
Props and state
Two kinds of data drive every React component.
Props (short for properties) are values passed *into* a component, like arguments to a function. They let one component show different things:
function ProductCard(props) { return <div><h3>{props.name}</h3><p>${props.price}</p></div>; }
You use it like an HTML tag: <ProductCard name="Mug" price={12} />. A component must never change its own props; they belong to whoever passed them in.
State is data a component *remembers* and can change, usually because the user did something. You create it with the useState hook:
const [count, setCount] = useState(0);
That gives you the current value (count, starting at 0) and a function to change it (setCount). When you call setCount(count + 1), React stores the new value and redraws the component with it. A simple counter button is:
<button onClick={() => setCount(count + 1)}>Clicked {count} times</button>
Rules that prevent most beginner bugs:
- Never change state directly (
count = 5does nothing useful); always use the setter - Keep state as small as possible; work out anything you can calculate from it
- If two components need the same state, keep it in their closest shared parent and pass it down as props
Props flow down from parent to child. To let a child change something, the parent passes down a function as a prop, and the child calls it.
The tutor gives hints, not finished answers. Log in to use it.