A key benefit of React is its unidirectional knowledge stream. This makes the stream of knowledge predictable, and helps keep away from sudden unintended effects from knowledge altering unexpectedly.
However what precisely does “unidirectional knowledge stream” imply in React? Let’s break it down:
The Information Flows Down
In React, dad or mum elements go knowledge to kids through props:
// Mother or father
operate Mother or father() {
const [value, setValue] = useState('Howdy');
return <Youngster worth={worth} />;
}
// Youngster
operate Youngster({worth}) {
return <h1>{worth}</h1>;
}
The dad or mum’s worth
state is handed down into the Youngster
through a prop. That is the “knowledge down” half.
Occasions Stream Up
When some knowledge wants to vary, occasions hearth and bubble up:
// Youngster
operate Youngster({worth, onUpdate}) {
return (
<button onClick={() => onUpdate('World')}>
Replace Worth
</button>
);
}
// Mother or father
operate Mother or father() {
const [value, setValue] = useState('Howdy');
const handleUpdate = (newValue) => {
setValue(newValue);
}
return <Youngster worth={worth} onUpdate={handleUpdate} />;
}
The onUpdate
callback propagates the occasion as much as the dad or mum. That is the “occasions up” half.
Advantages of Unidirectional Stream
This sample supplies a number of advantages:
- Predictable – Just one means knowledge might be modified
- Modular – Every element solely worries about its personal state
- Simple to purpose about – Keep away from cascading updates throughout a number of elements
Unidirectional stream enforces good React structure.
Bidirectional Stream Risks
Different frameworks use two-way binding. This results in cascading updates which can be onerous to hint:
A -> B -> C
B updates
C updates
A updates from C
B updates once more
React’s top-down stream retains knowledge altering in a single place solely.
Abstract
- React makes use of unidirectional knowledge stream
- Mother or father elements go knowledge down through props
- Youngster elements propagate occasions up
- This stream prevents cascading updates throughout elements
Studying to construction apps to observe unidirectional knowledge stream takes apply, however results in extra maintainable code.