Skills / Front-end apps with React / Props and state

Front-end apps with React, lesson 2 of 8

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 = 5 does 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.

Try it: Describe in words the state and props for a "Like" button that shows a heart and a like count. Which value is state, which component owns it, and what would you pass down as props?

Check yourself

1. What are props?

2. How should you change a state value called count?

3. Two sibling components need the same data. Where should the state live?