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

260
Views
React Hooks useCallback and useEffect causes infinite loop in react application
import axios from "axios";
import { useEffect, useState, useCallback } from "react";
export default function App() {
  const [user, setUser] = useState([]);
  const getUser = useCallback(async () => {
    let { data } = await axios.get(
      "https://jsonplaceholder.typicode.com/users"
    );
    setUser(data);
  }, [user]);

  useEffect(() => {
    getUser();
  }, [getUser]);
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

(i can remove getUser from useEffect dependency and remove useCallback as well this will work perfectly) but i wanna try putting getUser in useEffect dependency and while doing so need to wrap getUser in useCallback. in useCallback dependency, i put setUser it work fine but incase of putting user as useCallback dependency m getting infinite loop. why is not behaving same as setUser.

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

0

The effect will run if getUser changes:

useEffect(() => {
  //...
}, [getUser]);

And getUser will change if user changes:

const getUser = useCallback(async () => {
  //...
}, [user]);

And getUser changes user:

setUser(data);

So when the component renders, the effect executes, which calls getUser, which updates user, which changes getUser, which triggers the effect, which calls getUser, etc., etc.

The useCallback for getUser has no dependency on user, only on setUser. Change its dependency array to reflect that:

const getUser = useCallback(async () => {
  //...
}, [setUser]);

setUser doesn't change, so getUser won't change, so the effect won't be re-invoked.

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!