Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

177
Views
How to store socket on localStorage/use socket on different components on vanilla ReactJS for use in different components socket.io?

I want to store the socket so I can use it in different components. When I first set the socket on socket.io after login, I set the socket as a state under "socket" state and then store it on localStorage.

useEffect(() => {
        if(!socket) {
            setSocket(io(backendLink));
        };
    }, []) 

useEffect(() => {
        socket?.emit("newUser", localStorage.getItem('authToken'));
        localStorage.setItem('socket', JSON.stringify(socket));
    }, [socket])

Then in different components, where I did not initially set the socket. I use logic like this:

useEffect(() => {
        if(!socket) socket = localStorage.getItem('socket');
        socket.emit(...)
}, [userID])

Above, if the socket passed as props that was stored in state is null, i restore the socket from localStorage and use it to emit. However, I get Uncaught TypeError: Converting circular structure to JSON.

From what I understood, this is because I used JSON.stringify on something that cannot be converted and stored on localStorage this way i.e socket. I want to use vanilla reactjs to use the socket across as different files from the file i used setSocket(io(backendLink)). How to use socket.io across different components with vanilla reactJS(no context, completely vanilla)?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You should not stringify such objects, if you want to reference it across your application, you need to just to place it inside a React context after you saved it in the state. That way you can access it wherever you want across your application. There are other options too, but that's the safer one.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!