Correct Way to Invoke a PusherJs Instance in a ReactJs Functional Component

Yatharth Vyas
2 min readJan 24, 2021

PusherJs is a library for triggering and subscribing to real-time events based on WebSockets. In other words, you could think of it as a more comfortable, faster alternative to WebSockets.

There are a few things that you must be cautious of while working with Pusher to avoid overheads and reduce your bill total:

  • Declare the Pusher Variable and each Channel as a const
  • Subscribe to all the Channels when the Component is mounted
  • Make sure you unsubscribe from all the Channels while unmounting the Component
  • HIDE YOUR PUSHER KEY using an environment variable

Let us break this down:

Start by installing the pusher-js npm package.

npm install pusher-js

Make a .env file in your root directory to store your Pusher Key:

REACT_APP_PUSHER_KEY = ‘YOURKEYHERE’

Make sure you name this environment variable with the REACT_APP_ prefix; otherwise, ReactJs won’t be able to identify it. Now, this key can be invoked anywhere in your app via process.env. REACT_APP_PUSHER_KEY. This is a vital step that hides your API key in the final product.

Next, import Pusher in the functional component as

//Pusherimport Pusher from ‘pusher-js’;

To define and bind the Pusher channel, We make use of useEffect with zero dependencies (Equivalent to componentDidMount)

useEffect(()=>{// eslint-disable-next-line react-hooks/exhaustive-deps},[])

The comment // eslint-disable-next-line react-hooks/exhaustive-deps before the last line ensures that React doesn’t give us any warning for unused dependency.

Inside useEffect, declare Pusher as a const, and the Pusher’s key passed via the env variable that was set by us in the earlier step. The use of this environment variable is to hide your API key from malicious web scrapers who might misuse it in case they get access to it. Create an instance of Pusher as:

const pusher = new Pusher(process.env.REACT_APP_PUSHER_ENV, {    cluster: ‘ap2’})

Make sure you define this as a const because its value should not mutate.

Next, define each channel inside your useEffect as

const channel1 = pusher.subscribe(‘channel_name1’);

Again, we need to make sure that this channel is defined as a const. This is done to prevent the generation of multiple channels every re-render, which could increase your Pusher’s bill amount and cause multiple bind events triggering for each message.

To listen to events triggered in this channel, define a bind function. This is analogous to listen in WebSockets. Any code which you write inside this function will be executed each time you receive a message on the channel.

channel1.bind(‘private_channel_id’,function(data) {    console.log(data)    //Code which runs when your channel listens to a new message})

Finally, We must unsubscribe from the Channel to free up the used resources and optimize the number of concurrent listeners. This is where useEffect’s return function comes into play:

//return will be called upon Component Unmountreturn (() => {    pusher.unsubscribe(‘channel_name1’)    // pusher.unsubscribe(‘channel_name2’)})

That’s it. I hope this helped you guys. Please feel free to ask me any questions or provide me any feedback on this.

Thank you!

--

--