How can i access variable inside useEffect() hook

Viewed 3498

I am new to react and have initialized a variable named socket inside the use effect hook. I am trying to access it in my return statement. However i cant seem to access it. I am not sure how to do it. Thanks in advance!

function SendSocketData(socket) {

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

}


function App() {


  useEffect(()=> {
    let socket = io("http://localhost:3001",
    );


  },[]);





  return (
    <div className="App">
      <button onClick={()=>SendSocketData(socket)}>Send Data </button>
    </div>
  );
}

export default App;
4 Answers

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>
  );
}

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"));
  },[]);

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"));
    }
    

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