When I started coding, I mainly tried to catch up with syntaxis, but I needed to think about design and data flow when my projects grew. Just start coding something that is not working anymore.
To make this problem more specific, let’s discuss how React components can pass data between them. Let’s have some fun and imagine our React App as a group of experienced thieves from Ocean’s Eleven (I hope you are old enough to remember this movie with young Brad Pitt and George Cloney). The main character, Danny Ocean, a recently paroled thief, assembles a team of eleven skilled criminals to pull off an elaborate heist. Their target: robbing three of Las Vegas's most protected casinos—Bellagio, Mirage, and MGMGrand—simultaneously, all owned by the ruthless Terry Benedict. The team faces twists, close calls, and clever maneuvers to pull off one of the most daring heists in cinematic history. So, let’s imagine that React components are criminals who need to communicate secretly.
PS: I didn’t have time to watch this movie again, so I made up some examples instead of trying to find exact matches in the plot.
PS2: Ok. I finished watching half of the movie because it is so good.
Let's begin
1. Sharing Data Using Callbacks
In React, callbacks are a common way to share data between components, specifically from a child to its parent component. This pattern allows data to flow upward in the component hierarchy.
So, Rusty (Brad Pitt) goes to the race to find a retired con man, Saul Bloom and hands him a note with an invitation to participate in a heist. Saul decided to go after receiving a note.
// Danny (Parent Component)
const SaulBloom = () => {
const [secretMessage, setSecretMessage] = useState("");
// Callback to handle the message from Rusty
const handleRustyMessage = (message) => {
setSecretMessage(message);
};
return (
<div>
<h1>SaulBloom Secret Message: {secretMessage}</h1>
<Rusty sendToDanny={handleRustyMessage} />
</div>
);
};
// Rusty (Child Component)
const Rusty = ({ sendToDanny }) => {
const sendSignal = () => {
sendToSaul("All clear, move to the vault!"); // Sending secret signal
};
return (
<div>
<h2>Rusty: Sending Signal</h2>
<button onClick={sendSignal}>Send Secret Message</button>
</div>
);
};
2. Sharing Data Using State
However, what if information needs to be provided by all crew members? Let’s say the plan of the heist strategy is the shared state. The parent component (like Danny Ocean) manages the plan; all crew members need access to this information. Maybe they are using some paroled Google doc where Danny posted the plan, and members read it or updated it.
In React, the state is used to share and manage data within and between components. When the state is lifted to a common parent component, it can act as a single source of truth for its child components, enabling easy data sharing.
function CrewMeeting() {
const [plan, setPlan] = useState('Rob Bellagio at 11 PM');
const updatePlan = () => {
setPlan('Rob Bellagio and MGM Grand at 10 PM');
};
return (
<div>
<h1>🧭 Ocean's Eleven Heist Plan</h1>
<p>Current Plan: {plan}</p>
<button onClick={updatePlan}>Update Plan</button>
<div>
<CrewMember name="Danny Ocean" plan={plan} />
<CrewMember name="Rusty Ryan" plan={plan} />
<CrewMember name="Linus Caldwell" plan={plan} />
</div>
</div>
);
}
function CrewMember({ name, plan }) {
return (
<div >
<h3>👤 {name}</h3>
<p>📝 Plan: {plan}</p>
</div>
);
}
3. Sharing data using Custom Events
The plan is ready, and Ocean’s Eleven needs to check the casino. However, sending paper notes is too slow inside the building, and using a laptop is inconvenient. So they need to decide in advance about sure signs. For example, Frank Catto, who will play a discredited croupier in the plan, sees how Saul comes in and knows that the heist starts.
This example illustrates custom events in React. Here, they aren't built-in like vanilla JavaScript. However, you can still achieve a custom event-driven architecture using tools like the EventEmitter class or third-party libraries such as PubSub or EventTarget. In real life, we use this pattern, and the components that need to connect are not close, so props drilling doesn’t make sense. For example, if we need to show a sale banner after the module is closed.
Here is the code for Ocean’s metaphor.
// create eventBus.js
const eventBus = new EventTarget();
//event emitter component
function SaulBloom() {
const sendArrivalSignal = () => {
console.log('🕴️ Saul Bloom: Enters the casino as the wealthy foreigner.');
// Emit the custom event 'heistStart'
eventBus.dispatchEvent(new CustomEvent('heistStart', { detail: 'Saul has arrived' }));
};
return (
<div >
<h2>🕴️ Saul Bloom</h2>
<button onClick={sendArrivalSignal}>Enter Casino</button>
</div>
);
}
//event listener component
function FrankCatton() {
const [status, setStatus] = useState('Waiting for the signal...');
useEffect(() => {
// Listen for the 'heistStart' event
const handleHeistStart = (event) => {
console.log('🎲 Frank Catton: Received the signal! The heist begins.');
setStatus(`Signal received: ${event.detail}`);
};
eventBus.addEventListener('heistStart', handleHeistStart);
// Cleanup listener on component unmount
return () => {
eventBus.removeEventListener('heistStart', handleHeistStart);
};
}, []);
return (
<div>
<h2>🎲 Frank Catton</h2>
<p>{status}</p>
</div>
);
}
4. Sharing data using Broadcast Channel API
In the previous setup, team members could at least see each other, but what if they were located in different places and could not communicate directly? The only saver is Broadcast Channel API.
The Broadcast Channel API is a browser-native solution for sharing data between browser tabs, windows, or iframes from the exact origin. It acts as a communication channel to broadcast messages to all connected contexts.
Basher Tarr, the crew’s demolition expert and hacker at the most crucial point in the movie, turns off the electricity in the casino using an EMP device (Electromagnetic Pulse). Then everybody knows that it is the time to break into the vault.
//set up a channel to broadcast the EMP signal
const heistChannel = new BroadcastChannel("heistChannel");
// BasherTarr component and event emitter
function BasherTarr() {
const triggerEMP = () => {
const message = "EMP Triggered: Lights Out!";
heistChannel.postMessage(message); // Broadcast message to all tabs
console.log("💥 EMP Triggered - Message Sent");
};
return (
<div style={{ border: '2px solid red', padding: '10px', margin: '10px' }}>
<h2>🛠️ Basher Tarr (EMP Specialist)</h2>
<button onClick={triggerEMP}>💥 Trigger EMP</button>
</div>
);
}
//event receiver component
function CrewMember({ name }) {
const [status, setStatus] = useState("Waiting for signal...");
useEffect(() => {
// Listen for messages from the heist channel
const handleEMP = (event) => {
setStatus("Going into the vault");
};
heistChannel.addEventListener("message", handleEMP);
// Cleanup listener when component unmounts
return () => {
heistChannel.removeEventListener("message", handleEMP);
};
}, [name]);
return (
<div style={}>
<h3>👤 {name}</h3>
<p>🔌 Status: {status}</p>
</div>
);
}
5. Sharing data using EventBus
The previous two techniques work fantastically but can become messy if we have too many emitters, receivers, and events. During the heist, Livingston Dell, a surveillance expert, communicates with all crew members, telling them when it is time to act.
The EventBus is a simple publish/subscribe (pub/sub) system where components can emit events and others can listen. This avoids direct communication or props drilling while keeping the system clean and organized.
// TypedEventBus.js
class TypedEventBus {
constructor() {
this.eventBus = new EventBus();
}
/**
* Subscribes to a specific topic.
* @param {string} topic - Event name.
* @param {(payload: any) => void} listener - Listener function.
*/
subscribe(topic, listener) {
this.eventBus.subscribe(topic, listener);
}
/**
* Unsubscribes from a specific topic.
* @param {string} topic - Event name.
* @param {(payload: any) => void} listener - Listener function.
*/
unsubscribe(topic, listener) {
this.eventBus.unsubscribe(topic, listener);
}
/**
* Publishes an event with a typed payload.
* @param {string} topic - Event name.
* @param {any} payload - Event payload.
*/
publish(topic, payload) {
this.eventBus.publish(topic, payload);
}
}
// Create a singleton EventBus instance
const eventBus = new TypedEventBus();
export default eventBus;
// LivingstonDell.js
function LivingstonDell() {
const sendSignal = (topic, message) => {
eventBus.publish(topic, message);
};
return (
<div style={{ border: "2px solid green", padding: "10px", margin: "10px" }}>
<h2>📡 Livingston Dell (Surveillance Expert)</h2>
<button onClick={() => sendSignal("DannyOcean", "Move to the vault")}>
🎩 Signal Danny Ocean
</button>
<button onClick={() => sendSignal("RustyRyan", "Distract security")}>
🤵 Signal Rusty Ryan
</button>
<button onClick={() => sendSignal("LinusCaldwell", "Start the diversion")}>
🎭 Signal Linus Caldwell
</button>
</div>
);
}
I will be happy to any suggestions and corrections from colleges because I am pretty sure that there are many ways to refine this article.
I also want to create a part two of this article explaining the connections using iframes, integration-through-back-end-websocket, integration-through-back-end-long-polling, integration-through-storages (index db, for example), integration-through-URL, integration-through-third-dom-element. But it will be.
Thank you for reading
Top comments (0)