score:0

Accepted answer

a colleague came with this solution. using a reference for which as it is a reference is not enclosed.

const usesocketamountreceivedstate = (event: string): number => {
    const count = useref(0);
    const [state, setstate] = usestate(0);

    useeffect(() => {
        socket.on(event, () => {
            count.current++;
            setstate(count.current);
        });

        return (): void => {
            socket.off(event);
        };
    }, []);

    return state;
}

score:2

try putting an empty array as the second argument in the hook. you don't want this to register an event each time the component renders.

const usesocketamountreceivedstate = (event: string): number => {
    const [total, settotal] = usestate(0);

    useeffect(() => {
        socket.on(event, () => {
            console.log(total);
            settotal(total + 1);
        });

        return (): void => {
            socket.off(event);
        };
    }, [total]);

    return total;
}

update:

i made an update to my initial answer, and added total into the dependency array of the react hook.

note that the second argument, aka dependency array. it is an array that accepts state or prop. and it instructs react to run this hook each time any of the elements in the dependency array changes.

if you pass an empty array, then the hook will only be run at initial load, after the component mounts.

in your example, if you pass an empty array, it creates a closure. hence, the total value will always be the initial value.

so you can pass total into the dependency array, which will invoke the useeffect() to run only when total value changes. in your example, where there is no dependency array passed to the second argument, the useeffect() will run every single time, which is not what we want.

score:2

socket.on event has to be outside the useeffect function

const usesocketamountreceivedstate = (event: string): number => {
    const [total, settotal] = usestate(0);
    socket.on(event, () => {
        console.log(total);
        settotal(total + 1);
    });
    useeffect(() => {
        return (): void => {
            socket.off(event);
        };
    }, []);

    return total;
}

Related Query

More Query from same tag