Injecting singletons into your React components

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 (
      <h1>Click the button to subscribe</h1>
      <button onClick={props.eventManager.subscribe}>Click me</button>

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 (
      <App />

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.

0 0 votes
Article Rating
Notify of
Inline Feedbacks
View all comments