Search code examples
reactjswebsocketlodash

Save data from WebSocket messages only once per 5 seconds


I have a simple React component, where I subscribe to WebSocket message in useEffect hook:

  useEffect(() => {
    ws.onmessage = (response) => {
      const stream = JSON.parse(response.data)
      updateState([...stream ])
    }

    return () => ws.close()
  }, [])

And this is works just fine: I receive data from WebSocket and set it to state. But my problem is I receive really too many messages (more than I actually need), and I want to limit it to one state change per 5 seconds. Does not seem like I can use setTimeout or Lodash debounce/throttle here (or I can't find how). Are there any ways to do this?


Solution

  • You can throttle the onmessage handle to only allow one update per 5 seconds:

    useEffect(() => {
      ws.onmessage = _.throttle((response) => {
        const stream = JSON.parse(response.data)
        updateState([...stream])
      }, 5000, { leading: true })
    
      return () => ws.close()
    }, [])
    

    Note: using throttle is more fitting here. It means that every 5 second, one change would be applied. If you'll use debounce, and the rate of updates would be too fast, no update would be applied until the events would stop for awhile.