


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
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.
// 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> ); };
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.
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> ); }
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.
// 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing
