Unidirectional data flow means data moves one direction only: parent → child via props. Children cannot modify parent state directly; they must use callback functions. This makes state changes predictable and debugging easier.
What is Unidirectional Data Flow:
Key Principles:
Props are Immutable: Child components receive props but cannot change them
State Ownership: Each piece of state is owned by one component; changes only affect its children
Callbacks for Updates: Children communicate upward by calling functions passed as props
Single Source of Truth: Data originates from one place, making state predictable
Why It Matters:
Contrast with Two-Way Binding:
// Parent component owns the state
function ShoppingCart() {
const [items, setItems] = useState([]);
const [total, setTotal] = useState(0);
// Callback passed to child for upward communication
const addItem = (product) => {
setItems([...items, product]);
setTotal(total + product.price);
};
const removeItem = (id) => {
const item = items.find(i => i.id === id);
setItems(items.filter(i => i.id !== id));
setTotal(total - item.price);
};
return (
<div>
{/* Data flows DOWN via props */}
<ProductList onAddItem={addItem} />
{/* State passed down, callback passed for removal */}
<CartItems
items={items} // Data flows down
onRemove={removeItem} // Callback for upward communication
/>
<CartTotal total={total} />
</div>
);
}