Using CustomEvent for Global Event Broadcasting in Frontend Development (React & Vue)
This article explains how to leverage the JavaScript CustomEvent API to create and dispatch custom events for efficient, decoupled communication between components in complex React and Vue applications, providing syntax details, practical code examples, and guidance on appropriate usage scenarios.
Component communication is crucial in frontend development, and when component hierarchies become complex, using the native CustomEvent API offers a simple yet powerful way to broadcast messages across the application.
By creating and dispatching a CustomEvent, developers can send custom data without tightly coupling components, which reduces risk and speeds up development.
Implementation example:
const customEvent = new CustomEvent('yourEventName', {
detail: { key: 'myKey', value: 'newValue' } // custom data
});
window.dispatchEvent(customEvent); // push messageTo receive the event, add a listener on window:
window.addEventListener('yourEventName', (event) => {
const { key, value } = event.detail;
if (key === 'myKey') {
console.log('Detected localStorage change:', value);
}
});The basic syntax is new CustomEvent(eventType, eventInit), where eventInit may contain detail, bubbles, and cancelable properties.
Use cases include component‑to‑component communication in both React and Vue, as well as extending native browser events for global sharing.
Vue example:
UserProfile.vue
<template>
<div>
<input v-model="username" @input="updateUser" placeholder="Enter your name" />
</div>
</template>
<script>
export default {
data() { return { username: '' }; },
methods: {
updateUser() {
const customEvent = new CustomEvent('userUpdated', {
detail: { name: this.username }
});
window.dispatchEvent(customEvent);
}
}
};
</script>Notification.vue
<template>
<div v-if="message">{{ message }}</div>
</template>
<script>
export default {
data() { return { message: '' }; },
mounted() {
window.addEventListener('userUpdated', (event) => {
const { name } = event.detail;
this.message = `User name has been changed to ${name}`;
});
},
beforeDestroy() {
window.removeEventListener('userUpdated', this.eventListener);
}
};
</script>React example:
UserProfile.jsx
import React, { useState } from 'react';
const UserProfile = () => {
const [username, setUsername] = useState('');
const updateUser = (e) => {
const newName = e.target.value;
setUsername(newName);
const customEvent = new CustomEvent('userUpdated', {
detail: { name: newName }
});
window.dispatchEvent(customEvent);
};
return (
<div>
<input value={username} onChange={updateUser} placeholder="Enter your name" />
</div>
);
};
export default UserProfile;Notification.jsx
import React, { useEffect, useState } from 'react';
const Notification = () => {
const [message, setMessage] = useState('');
useEffect(() => {
const eventListener = (event) => {
const { name } = event.detail;
setMessage(`User name has been changed to ${name}`);
};
window.addEventListener('userUpdated', eventListener);
return () => {
window.removeEventListener('userUpdated', eventListener);
};
}, []);
return <div>{message}</div>;
};
export default Notification;In conclusion, while frameworks provide their own communication mechanisms, CustomEvent is a lightweight alternative that can be especially useful in time‑critical or highly decoupled scenarios.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Rare Earth Juejin Tech Community
Juejin, a tech community that helps developers grow.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
