State and Props
State and props are the pair that shares parent state with a child. The parent owns the state, and the child shows it through props.
Pass state as a prop
Display receives the current count as a prop.
<Display count={count} />Read the prop in the child
Display shows the count from props.
function Display(props) {
return <p>Count: {props.count}</p>;
}The parent owns the state
The parent creates the state. The child only shows it.
const [count, setCount] = useState(0);Example
import { useState } from 'react';
function Display(props) {
return <p>Count: {props.count}</p>;
}
export default function App() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
}
return (
<div>
<Display count={count} />
<button onClick={handleClick}>Add 1</button>
</div>
);
}Key points
- State lives in the parent component.
- The parent passes the value down as a prop.
- The child reads the value from props.
- When the state changes, the child renders again too.
- The child never changes the prop itself.
In this example, Display takes props and shows the count. App starts count at 0. handleClick calls setCount with count + 1. App passes count to Display as a prop. App also returns a button. A click runs handleClick. React renders again, and Display shows Count: 1.
Note
Props stay read-only, even when they carry state.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
How does a child show the parent state?