Member-only story

React Hooks: Managing Web Sockets with useEffect and useState

Rundown of React Hooks and applying them to a real-time chat room simulation

Ross Bulat
8 min readNov 5, 2018

Hooks in React have triggered a transition in how React developers structure their projects; a catalyst for adopting functions in place of classes. This article will visit 2 hooks, useState and useEffect, to simulate a real-time chat room environment utilising socket.io and Express, with the aim of demonstrating how these hooks work.

We will then examine the behaviour of our hooks and showcase an additional demo to improve our room joining behaviour (spoiler: bottom of article). The demos can be easily replicated, and I will list the commands for setting up the project for anyone to use after the explanation.

Without getting ahead of ourselves, let’s examine the first demo, where we will see how useState and useEffect can be used with a web socket to control the mounting, re-rendering and unmount process. The end result is the following:

Top Left: Express Server. Bottom Left: Javascript Console. Right: React App

Demo showcasing how useState and useEffect hooks manage a websocket connection

Hooks Overview

In the above demo we are using hooks in the following ways:

useState

useState is used to set our component state variables. We define these hooks as soon as we open our function declaration. No classes are used in this demo, nor do we need to use setState() for updating state:

function App() {   const [messageCount, setMessageCount] = useState(0);
const [theme, setTheme] = useState('dark');
const [inRoom, setInRoom] = useState(false);

...

Let’s look at how a useState hook is defined, and then compare it to standard React syntax.

  • useState utilises destructuring assignment syntax (read more about it here). What this syntax allows us to do is unpack values from an array into distinct variables. For each hook above, we are defining 2 variables in its array, which we can then use in our App function…

--

--

Ross Bulat
Ross Bulat

Written by Ross Bulat

Programmer and Author. @ Parity Technologies, JKRB Investments

Responses (10)

Write a response