From dd308ecab0c0aaea66b4603a1fcff3fec645fe29 Mon Sep 17 00:00:00 2001 From: Mitchell McCaffrey Date: Fri, 1 Jan 2021 13:06:56 +1100 Subject: [PATCH] Added debounce to useNetworkedState --- src/helpers/useNetworkedState.js | 29 +++++++++++++++++++++-------- 1 file changed, 21 insertions(+), 8 deletions(-) diff --git a/src/helpers/useNetworkedState.js b/src/helpers/useNetworkedState.js index eefbb75..452ee23 100644 --- a/src/helpers/useNetworkedState.js +++ b/src/helpers/useNetworkedState.js @@ -1,22 +1,35 @@ -import { useEffect, useState, useCallback } from "react"; +import { useEffect, useState, useRef, useCallback } from "react"; -function useNetworkedState(defaultState, session, eventName) { +import useDebounce from "./useDebounce"; + +function useNetworkedState( + defaultState, + session, + eventName, + debounceRate = 100 +) { const [state, _setState] = useState(defaultState); // Used to control whether the state needs to be sent to the socket - const [dirty, setDirty] = useState(false); + const dirtyRef = useRef(false); // Update dirty at the same time as state const setState = useCallback((update, sync = true) => { _setState(update); - setDirty(sync); + dirtyRef.current = sync; }, []); + const eventNameRef = useRef(eventName); useEffect(() => { - if (session.socket && dirty) { - session.socket.emit(eventName, state); - setDirty(false); + eventNameRef.current = eventName; + }, [eventName]); + + const debouncedState = useDebounce(state, debounceRate); + useEffect(() => { + if (session.socket && dirtyRef.current) { + session.socket.emit(eventName, debouncedState); + dirtyRef.current = false; } - }, [session.socket, dirty, eventName, state]); + }, [session.socket, eventName, debouncedState]); useEffect(() => { function handleSocketEvent(data) {