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 id="SaulBloom-Secret-Message-secretMessage">SaulBloom Secret Message: {secretMessage}</h1> <rusty sendtodanny="{handleRustyMessage}"></rusty> </div> ); };
// Rusty (Child Component) const Rusty = ({ sendToDanny }) => { const sendSignal = () => { sendToSaul("All clear, move to the vault!"); // Sending secret signal }; return ( <div> <h2 id="Rusty-Sending-Signal">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 id="SaulBloom-Secret-Message-secretMessage">SaulBloom Secret Message: {secretMessage}</h1> <rusty sendtodanny="{handleRustyMessage}"></rusty> </div> ); };
// Rusty (Child Component) const Rusty = ({ sendToDanny }) => { const sendSignal = () => { sendToSaul("All clear, move to the vault!"); // Sending secret signal }; return ( <div> <h2 id="Rusty-Sending-Signal">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 id="Ocean-s-Eleven-Heist-Plan">? 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> <crewmember name="Rusty Ryan" plan="{plan}"></crewmember> <crewmember name="Linus Caldwell" plan="{plan}"></crewmember> </div> </div> ); }
function CrewMember({ name, plan }) { return ( <div> <h3 id="name">? {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 id="Saul-Bloom">?️ 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> </div>
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!

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.


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

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version
Useful JavaScript development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
