Sometimes you’ll need to use the singleton pattern in your applications and there is an easy way to inject these into your React components. This way is by setting a default prop as the Singelton.
If we have a singleton named MyEventManager for handling events globally throughout our app your component could look like this:
function App(props) {
return (
<div>
<h1>Click the button to subscribe</h1>
<button onClick={props.eventManager.subscribe}>Click me</button>
</div>
);
}
You can see the component calls the eventManager subscribe function when the user clicks the button.
But if the parent of the App component doesn’t pass down an event manager like this:
function AppParent() {
return (
<div>
<App />
</div>
)
}
Then you can use default props to inject our event manager:
App.defaultProps = {
eventManager: MyEventManager
}
Where the class MyEventManger might look like:
const MyEventManager = {
subscribe: function() {
console.log('New subscriber added')
}
}
This is just one way of having a global singleton in your React apps and can be particularly useful.