javascript / intermediate
Snippet
Robust Dependency Injection with Symbols
Using unique Symbols as injection keys prevents naming collisions in large-scale applications. Unlike string keys, Symbols are guaranteed to be unique, ensuring that provided values are not accidentally overwritten by other components or libraries.
snippet.js
1
2
3
4
5
6
7
const USER_KEY = Symbol('UserConfig');// Providerprovide(USER_KEY, { id: 1, name: 'Alex' });// Consumerconst user = inject(USER_KEY);
vue
Breakdown
1
Symbol('UserConfig')
Creates a unique, non-clashing identifier used as the key for the provide/inject mechanism.