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

256
Views
Mutating state values in useEffect isn't working (react 16+, react-router v6)

I'm trying to fetch a url when the page first loads and when the location changes. The first load works fine. The record id is pulled from params and when that changes, useEffect gets called again to reset state and reload the new records. However, all of the set* calls in useEffect aren't doing anything as the loadData() method sees the old data still (hasMoreData=false, dataRecords=[...]).

export function MyComponent(props) {
  const [hasMoreData, setHasMoreData] = useState(true);
  const [dataRecords, setDataRecords] = useState([]);
  const [currentPage, setCurrentPage] = useState(1);
  const params = useParams();
  const location = useLocation();
  const { id } = params;

  const loadData = useCallback((page = 1) => {
    if (hasMoreData) {
      fetchSomeData(`api/records?id=${id}&page=${page}`).then((response) => {
        const { data } = response;
        // note: pagination logic omitted for clarity
        if (data && data.length > 0) {
          setDataRecords(data);
        } else {
          setHasMoreData(false);
        }
      });
    }
  }, [id, dataRecords, hasMoreData]);
  
  useEffect(() => {
    // id param has changed, or its the first load - reset all fields, then fetch new data
    setHasMoreData(true);
    setDataRecords([]);
    setCurrentPage(1);
    loadData(currentPage);
  }, [location]);

  // ...currentPage managed via infiniteScroll
};

What am I doing wrong here?

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

0

Comments on the original question lead me to a better way to achieve what I was after. I needed to detect a location change, pagination changes and loading data on initial page load and useCallback wasn't the best way to go about this because the state changes are asynchronous and it didn't see the new values yet. Instead I used a separate useEffect() for changes to the location so I can reset the internal state data, and a second useEffect() to handle changes to currentPage rather than calling loadData() directly.

export function MyComponent(props) {
  const [hasMoreData, setHasMoreData] = useState(true);
  const [dataRecords, setDataRecords] = useState([]);
  const [currentPage, setCurrentPage] = useState(1);
  const params = useParams();
  const location = useLocation();
  const { id } = params;

  useEffect(() => {
    // location changed, reset all data
    setHasMoreData(true);
    setDataRecords([]);
    setCurrentPage(1);
  }, [location]);
  
  useEffect(() => {
    // id param has changed, or its the first load - reset all fields, then fetch new data
    loadData(currentPage);

    function loadData(page = 1) {
      if (hasMoreData) {
        fetchSomeData(`api/records?id=${id}&page=${page}`).then((response) => {
          const { data } = response;
          // note: pagination logic omitted for clarity
          if (data && data.length > 0) {
            setDataRecords(data);
          } else {
            setHasMoreData(false);
          }
        });
      }
    }
  }, [currentPage]);

  // ...currentPage managed via infiniteScroll
};
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!