Maintaining a websocket connection in state with React and Recoil.js

Viewed 566

I'm looking for a practical way to maintain a websocket connection in state with Recoil.

My idea is to put the websocket into an atom:

import useWebSocket from 'react-use-websocket';
import { atom, selector } from 'recoil';

const socketUrl =
  'wss://xxx.com';

const webSocket = useWebSocket(socketUrl, {
  onOpen: () => console.log('opened'),
  //Will attempt to reconnect on all close events, such as server shutting down
  shouldReconnect: (closeEvent) => true,
});

// If the page has been archived before, the id in the archive
export const webSocketAtom = atom({
  key: 'webSocket',
  default: webSocket,
});

Is it a good approach or does I break some rules there?

1 Answers

Recoil currently can't handle class instances, that would be the only rule.

Your code of course doesn't work though because you are using a hook outside of a component, but other than that you should be able to save the returned object of useWebSocket inside an atom.

Related