Last active
October 23, 2020 01:58
-
-
Save itsMapleLeaf/6b4be5a792d48eee9b72b5ccf1df073e to your computer and use it in GitHub Desktop.
websockets with hooks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const socketRef = useRef(); | |
| const [connected, setConnected] = useState(false); | |
| // this ref based off of the "connected" state lets us read it in `connect` | |
| // without having to declare it as a dependency | |
| const connectedRef = useRef(connected); | |
| useEffect(() => { | |
| connectedRef.current = connected; | |
| }); | |
| const connect = useCallback(function connect() { | |
| if (connectedRef.current) return; | |
| const socket = (socketRef.current = new WebSocket("...")); | |
| socket.onopen = () => setConnected(true); | |
| socket.onclose = () => setConnected(false); | |
| socket.onerror = () => setConnected(false); | |
| socket.onmessage = () => { | |
| // use callback updater, so this callback doesn't need to depend on current state | |
| setMessages((messages) => [ | |
| ...messages, | |
| { message, created_by, created_at }, | |
| ]); | |
| }; | |
| }, []); | |
| const disconnect = useCallback(function disconnect() { | |
| setConnected(false); | |
| if (!socketRef.current) return; | |
| // remove listeners so funky stuff doesn't happen | |
| socketRef.current.onopen = null; | |
| socketRef.current.onmessage = null; | |
| socketRef.current.onclose = null; | |
| socketRef.current.onerror = null; | |
| socketRef.current.close(); | |
| }, []); | |
| function send(msg) { | |
| socketRef.current?.send(msg); | |
| } | |
| useEffect(() => { | |
| connect(); | |
| return () => disconnect(); | |
| }, [connect, disconnect]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment