score:1

Accepted answer

you first need to declare the socket object as a variable with usestate():

import react, { usestate, useeffect } from 'react';

const [socket, setsocket] = usestate(null);

then assign it with useeffect():

  useeffect(()=> {
    setsocket(io("http://localhost:3001"));
  },[]);

score:1

you can define the variable outside of the component or declare it inside then function and the assign the value to it inside useeffect.

function sendsocketdata(socket) {

  socket.emit("hello", "world");

}

let socket;

function app() {

  useeffect(()=> {
    socket = io("http://localhost:3001",)
  }, []);

  return (
    <div classname="app">
      <button onclick={()=>sendsocketdata(socket)}>send data </button>
    </div>
  );
}

export default app;

or

function app() {
  let socket;

  useeffect(()=> {
    socket = io("http://localhost:3001",)
  }, []);

  return (
    <div classname="app">
      <button onclick={()=>sendsocketdata(socket)}>send data </button>
    </div>
  );
}

score:1

make it in:

    function app() {
        const socket = io("http://localhost:3001",
    );
    useeffect(()=> {}

or use usestate:

    function app() {
        const [socket, setsocket ] = usestate(null);

    );
    useeffect(()=> {
        setsocket(io("http://localhost:3001"));
    }
    

score:1

you could try to store the socket in a variable state. something like this:

    import react, { usestate, useeffect } from "react";
    import io from "socket.io-client";
    
    function app() {
      const [socket, setsocket] = usestate();
    
      useeffect(() => {
        setsocket(io("http://localhost:3001"));
      }, []);

      function sendsocketdata(socket) {
         socket.emit("hello", "world");
      }
    
      return (
          <div classname="app">
            <button onclick={()=>sendsocketdata(socket)}>send data </button>
          </div>
      );
    }
    
    export default app;

Related Query

More Query from same tag