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

338
Views
Async/Await in useEffect(): how to get useState() value?

I have the following code snippet. Why is my limit always 0 in my fetchData? If I were to console.log(limit) outside of this function it has the correct number. Also If I dont use useState but a variable instead let limit = 0; then it works as expected

I also added limit as a dependency in useEffect but it just keeps triggering the function

  const [currentData, setData] = useState([]);
  const [limit, setLimit] = useState(0);

const fetchData = async () => {
    console.log(limit);
    const { data } = await axios.post(endpoint, {
      limit: limit,
    });
    setData((state) => [...state, ...data]);
    setLimit((limit) => limit + 50);
  };

  useEffect(() => {
    fetchData();
    window.addEventListener(`scroll`, (e) => {
      if (bottomOfPage) {
        fetchData();
      }
    });
  }, []);
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

When you pass an empty dependency array [] to useEffect, the effect runs only once on the initial render:

If you pass an empty array ([]), the props and state inside the effect will always have their initial values.

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. This tells React that your effect doesn’t depend on any values from props or state, so it never needs to re-run. This isn’t handled as a special case — it follows directly from how the dependencies array always works.

useEffect docs

The initial state of limit is 0 as defined in your useState call. Adding limit as a dependency will cause the effect to run every time limit changes.

about 4 years ago · Juan Pablo Isaza Report

0

One way to get around your issue is to wrap the fetchData method in a useCallback while passing the limit variable to the dependency array.

You can then pass the function to the dependency array of useEffect and also return a function from inside of useEffect that removes event listeners with outdated references.

You should also add a loading variable so that the fetchData function doesn't get called multiple times while the user is scrolling to the bottom:

const [currentData, setData] = useState([]);
const [limit, setLimit] = useState(0);
const [loading, setLoading] = useState(false);

const fetchData = useCallback(async () => {
    console.log(limit);
    // Prevent multiple endpoint calls when scrolling near the end with a loading state
    if (loading) {
        return;
    }

    setLoading(true);
    const { data } = await axios.post(endpoint, { limit });
    setData((state) => [...state, ...data]);
    setLimit((limit) => limit + 50);
    setLoading(false);
}, [limit, loading]);

// Make the initial request on the first render only
useEffect(() => {
    fetchData();
}, []);

// Whenever the fetchData function changes update the event listener
useEffect(() => {
    const onScroll = (e) => {
        if (bottomOfPage) {
            fetchData();
        }
    };

    window.addEventListener(`scroll`, onScroll);

    // On unmount ask it to remove the listener
    return () => window.removeEventListener("scroll", onScroll);
}, [fetchData]);
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!