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

129
Views
useEffect goes in an infinite loop. How to fix this?

Please alter this code so that useEffect does not keep calling itself again and again. Here, I am fetching data from the backend and updating state within the useEffect, which itself is the dependency. Is there some easy way to fix it?

My use case: I use a form to add a post and once I submit the form, I want it to show the updated list of posts right away. 'Posts' is a component where the updated list of posts are passed as props and each individual post is rendered within component 'Post'. So, I want to pass the updated list of post to 'Posts' once the form is submitted

useEffect(() => {
    async function readPosts(){
      try {
        const res = await axios.post(backendLink + '/post/profile/read');
        setPosts(res.data.posts);
      } catch (err) {
        console.log(err);
      }
    }
    readPosts();
  }, [posts])
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

useEffect(() => {
    async function readPosts(){
      try {
        const res = await axios.post(backendLink + '/post/profile/read');
        setPosts(res.data.posts);
      } catch (err) {
        console.log(err);
      }
    }
    readPosts();
  }, []) // Change here
about 4 years ago · Juan Pablo Isaza Report

0

This is whats happening right now in your code.

useEffect fires when the "posts" value change. the useEffect changes the "posts" which triggers useEffect because useEffect changed "posts"

this is an infinite loop. remove [posts] from dependency and find a workaround.

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!