JS Guide
HomeQuestionsSearchResources
Search

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionsreact
Prev
react
junior
data-flow

What is unidirectional data flow in React and why is it important?

data-flow
unidirectional
props
state
one-way-binding
Quick Answer

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.

Detailed Explanation

What is Unidirectional Data Flow:

  • Data flows in one direction: parent → child via props
  • Child components cannot modify received props (read-only)
  • To update parent state, children call callback functions passed as props
  • Also called 'one-way data binding'

Key Principles:

  1. Props are Immutable: Child components receive props but cannot change them

  2. State Ownership: Each piece of state is owned by one component; changes only affect its children

  3. Callbacks for Updates: Children communicate upward by calling functions passed as props

  4. Single Source of Truth: Data originates from one place, making state predictable

Why It Matters:

  • Predictable: You always know where data comes from
  • Debuggable: Easy to trace data flow and find issues
  • Maintainable: Clear data ownership prevents spaghetti code

Contrast with Two-Way Binding:

  • Angular/Vue v-model syncs model↔view automatically
  • React requires explicit state updates
  • Two-way can be convenient but harder to debug

Code Examples

Unidirectional flow: Parent → Child → Callback
// 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>
  );
}

Resources

React Docs - Sharing State Between Components

docs

Unidirectional Data Flow in React - GeeksforGeeks

article

Related Questions

What are props in React and how do you pass data between components?

junior
props

What is React Context and when should you use it?

mid
context
Previous
Why would you choose React over other frameworks like Vue or Angular?