Home >Web Front-end >JS Tutorial >From Heist Strategy to React State: How data flows between components
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
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> ); };
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.
// 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> ); };
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.
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> ); }
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.
// 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> ); }
// LivingstonDell.js function LivingstonDell() { const sendSignal = (topic, message) => { eventBus.publish(topic, message); }; return ( <div> <p>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. <br> 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.</p> <p>Thank you for reading</p>
The above is the detailed content of From Heist Strategy to React State: How data flows between components. For more information, please follow other related articles on the PHP Chinese website!