0
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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Why pass setUser as dependency intead of [] ?
@NiceBooks: Because it’s a dependency in the function. Linters/transpilers will even complain if you don’t. Though it’s certainly possible it’s not needed, and won’t change, it’s still good practice to include relevant dependencies because if it ever does change then the function would otherwise be referencing a stale version.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.