Props and state

Pass data with props

Give a child component data through JSX attributes and read those values from the component parameter.

Props are the inputs to a component. The parent chooses them for the current render.

function Greeting({ name, unreadCount }) {
  return (
    <p>
      Hello, {name}. You have {unreadCount} unread messages.
    </p>
  )
}

export default function App() {
  return <Greeting name="Ada" unreadCount={3} />
}

Quoted values are strings. Braces pass JavaScript values, so unreadCount={3} passes a number.

When App renders again with different props, React calls Greeting again. The child receives a new snapshot of those values and returns matching JSX.

Props can contain strings, numbers, objects, arrays, functions, and JSX. Keep the interface focused. If a component needs many unrelated props, it may have too many responsibilities.

The child should not need to know where the data came from. It might come from state, a route, or a server response. It only needs the contract represented by its props.

The quoting matters more than it looks. JSX does not infer a number from a quoted attribute. If you write unreadCount="3", the child receives a string, not a number. That can break comparisons and math later.

You can also pass JSX as a prop when a child needs a slot for custom content:

<Panel title="Inbox" action={<button>Mark all read</button>} />

The child receives action like any other prop and renders it where the layout needs it.

Callback props follow the same rules. Pass onSave={handleSave}, not onSave={handleSave()}. The parent gives the child a function to call later, just like passing data down with a regular prop.

Rename a prop in the parent and TypeScript or PropTypes will flag the mismatch in the child. Even without types, React DevTools shows exactly what each component received on the last render.

Render two greetings with different values in App. Then deliberately pass unreadCount="3" and inspect the type in React DevTools. You should see "3" as a string, not 3 as a number.

Lesson completed