← React Beginner Questions - Set 5 Q46

What is the difference between stateful and stateless components?

React Beginner Questions - Set 5

The distinction is only about who holds the data. A stateless component is a pure function of its props.

Example

// Stateless: props in, JSX out, no memory
function Total({ items }) {
  return <p>{items.reduce((sum, i) => sum + i.price, 0)} EUR</p>;
}

// Stateful: owns data that changes over time
function Cart() {
  const [items, setItems] = useState([]);
  return (
    <>
      <button onClick={() => setItems(i => [...i, { price: 10 }])}>Add</button>
      <Total items={items} />
    </>
  );
}

What to notice

← Back to the question list