Props and state are both plain JavaScript data that influence what a component renders, but they differ in ownership. Props (properties) - Passed from a parent component to a child, like function arguments. - Read-only for the child: a component must never modify its props. - When the parent re-renders with new props, the child re-renders with the new values. - Can include data, callback functions and even other components (children). function ProductCard({ name, price, onAdd }: { name: string; price: number; onAdd: () => void }) { return ( <div> <h3>{name}</h3> <p>₹{price}</p> <button onClick={onAdd}>Add to cart</button> </div> ); } State - Data owned and managed by a component itself, which can change over time (user input, toggles, fetched data). - Created with hooks: useState or useReducer. - Updating state with the setter schedules a re-render with the new value. function Counter() { const [count, setCount] = useState(0); return <button onClick={() => setCount(c => c + 1)}>Clicked {count} times</button>; } How they work together - State lives in the component that owns the data; it is passed down to children as props; children request changes by calling callback props (data flows down, events flow up). - When two siblings need the same data, lift the state up to their closest common parent. Important rules - Never mutate state directly (state.items.push(x)); create new objects or arrays (setItems([...items, x])) so React detects the change. - Use the functional updater (setCount(c => c + 1)) when the new state depends on the previous state. - State updates are batched and applied on the next render, so reading state right after setState still shows the old value. - Do not copy props into state unless you intentionally want an initial value only; derive values during render instead. - Keep state minimal: compute derived values (totals, filtered lists) from existing state rather than storing duplicates. Summary: props are inputs from outside; state is a component's own changing memory.
Ravindra Wadile · · 0 likes