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

--

--

Ross Bulat
Ross Bulat

Written by Ross Bulat

Programmer and Author. @ Parity Technologies, JKRB Investments

Responses (10)