Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i access variable inside useEffect() hook

Tags:

reactjs

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;
like image 350
json Avatar asked Sep 29 '26 21:09

json


2 Answers

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"));
  },[]);
like image 154
Or Assayag Avatar answered Oct 02 '26 10:10

Or Assayag


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>
  );
}
like image 28
samehanwar Avatar answered Oct 02 '26 09:10

samehanwar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!