One-way data binding in React means that data flows in a single direction, from the component’s state or props down to the user interface (UI).
How One-Way Data Binding Works:
- The state (data) is the single source of truth.
- Changes in state or props → UI gets updated automatically.
- UI changes do not directly modify the state; instead, an event (e.g., onChange) triggers a function to update the state.
Example of One-Way Data Binding:
javascriptCopyEditimport { useState } from 'react';
function App() {
const [text, setText] = useState('Hello');
const handleChange = (event) => {
setText(event.target.value); // Updates state when input changes
};
return (
<div>
<input type="text" value={text} onChange={handleChange} />
<p>{text}</p>
</div>
);
}
Explanation:
- State (
text
) → Input field value:
The value of the input is controlled by thetext
state. - User types in input →
handleChange
function updates state:
This updates the state, which re-renders the component, updating the input and paragraph. - Data flows in one direction:
State → UI.
Changes in the UI trigger state updates, but UI cannot directly change the state.
Key Points:
Feature | Description |
---|---|
Data Flow | One-directional: State/Props → UI |
Controlled Components | Form inputs controlled by state |
State is Central | State is the single source of truth |
UI Updates Automatically | When state changes, UI re-renders |
Explicit Updates | UI cannot modify state directly; state is updated via event handlers |
Why React Uses One-Way Data Binding:
✅ Predictability: Easier to understand and debug.
✅ Better Control: State management is more centralized.
✅ Performance: React re-renders only the necessary parts efficiently.
Comparison: One-Way vs Two-Way Data Binding
One-Way Data Binding (React) | Two-Way Data Binding (e.g., Angular) |
---|---|
Data flows in one direction (State → UI) | Data flows in both directions (UI ↔ State) |
State is updated using events | UI modifies state automatically |
Controlled and predictable | Automatic but can be harder to debug |
React (default approach) | Angular, Vue (optional) |
Summary:
One-way data binding in React means that data moves from the component’s state/props to the UI.
To change the state, an event handler updates the state, which re-renders the UI with new data.