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

178
Views
react native useEffect run into dead loop:
export default function CreatePage() {
let [state,setState]=useState({})
let flag=true
useEffect(()=>{
    if(flag){
        axios.get('http://192.168.43.151:3001/data').then((res)=>
    {
        console.log(res.data)
        setState({...res.data})
        flag=false
        console.log(false)
      
    }
    ).catch((err)=>{console.log(err)}).finally(()=>{flag=false})

    }

    
})


return (
    <View >
        <Text>hh</Text>
        <Icon name="heart" size={24} color="#4F8EF7" />
        <Text>first page</Text>
        <Text>{state.name}</Text>
        
    </View>
)

}

after the code is executed ,the terminal continues showing :

    {"age": 25, "name": "connor", "password": "123456"}
 LOG  false
 LOG  {"age": 25, "name": "connor", "password": "123456"}
 LOG  false
 LOG  {"age": 25, "name": "connor", "password": "123456"}
 LOG  false

i have confusion about this ,useEffect function should be rendered once .However ,it seems continuing to be redered .

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

0

to execute useEffect only once you have to add dependency array with no dependency. Something like this:

useEffect(() => {
    // this code will execute only once after first render.
   // some code...
}, [])
about 4 years ago · Juan Pablo Isaza Report

0

You did not add a dependency array to the useEffect function. Therefore, it is bound to be an infinite reRendering.

And react does not recommend let. Use the status value.

You can add a dependency array

const [state,setState] = useState({});
const [flag,setFlag] = useState(true);
useEffect(()=>{
    if(flag){
        axios.get('http://192.168.43.151:3001/data').then((res)=>
    {
        console.log(res.data)
        setState({...res.data})
        setFlag(false)
        console.log(false)
      
    }
    ).catch((err)=>{console.log(err)}).finally(()=>{flag=false})

    }

    
},[])


if(flag) {
   return <LoadingElem />
}

...
about 4 years ago · Juan Pablo Isaza Report

0

If you want to run an effect and clean it up only once (on mount and unmount), you can pass an empty array ([]) as a second argument to the useEffect.

useEffect(() => {}, [])
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!