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

285
Views
Why does my app connect to my TCP server multiple times in my react native app?

When I run the code, it connects to my TCP server multiple times even though I am expecting it to connect only once

import React, { useEffect, useState, Component }  from 'react';
import { Text, View, StyleSheet, Image, Button } from 'react-native';
import { Touchable, TouchableOpacity } from 'react-native-web';
var net = require('react-native-tcp-socket');
var cert= require('./certificate.pem');


export default function AssetExample() {;
    const [out, outfunc] = useState('Connecting...');
    const [count, countfunc] = useState(0);
        const client = net.createConnection(
        { port: 4242, host: '192.168.1.108', tls: true, tlsCheckValidity: false, tlsCert: cert  },
        () => {
        console.log("Connected");
        client.write("1");
        client.write("2");
        client.write("3");
        client.write("4");
        })
        client.on("data", function (data) {
            console.log(data);
            var dat = data.toString();
            countfunc(count + 1);
            outfunc(out + "\n" + dat);
            if (data == "") {
              console.log("discon");
            }
            if (dat == "ACCGNT") {
              console.log("GRANTED");
            if (dat == "ALRCON"){
                client.destroy();
            }
              
            }}); 
//            client.destroy();
        
    return (
        <View>
            <Text>{count}</Text>
          <Text>
            {out}
          </Text>
        </View>
      );

}

The output is also changing a lot and it does not seem to follow how I programmed it to look. The output seems to be flicking from many other outputs.

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

0

React triggers your function multiple times during rendering. But doesn't rerender the UI. so whatever js code inside the function will be executed every time. SO to avoid you need to move the connection logic to useEffect hook

useEffect(()=>{
// establish connection 
return ()=>{ 
// destroy connection
} 
},[])

Now the connection will happen only once. if you to reconnect based on some state. add that state in dependency array.

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!