1
  const handlePageChange = (page, itemCount) => {
    

   setActivePage(page); // This is how am updating my state variable 
 
   setItemsPerPage(itemCount); // This is how am updating my state variable 
  

  }

handlePageChange is called from onclick() , but it seems like activepage update is happening late ( it seems i am lagging by one) , if I go to 2nd page my state variable of active page will show 1

wangdev87
  • 8,611
  • 3
  • 8
  • 31
ricky
  • 125
  • 7
  • how did you check activePage variable update? – wangdev87 Dec 04 '20 at 10:04
  • @WilliamWang , by putting debugger , also by console.log(activePage) , i could see variable is not getting updated – ricky Dec 04 '20 at 10:13
  • Inside the handlePageChange function, if the parameters `page` and `itemCount` contain the correct values that you need then use them. State change doesn't happen immediately but only when the component is called the next time. – Guy Incognito Dec 04 '20 at 10:15

1 Answers1

4

Since setActivePage is the asynchronous method, you can't get the updated value immediately after setActivePage. You should use another useEffect with dependency to see the updated activePage.

const handlePageChange = (page, itemCount) => {
   setActivePage(page);
   console.log(activePage); // Old `activePage` value will be printed.
   ...
}
useEffect(() => {
  console.log(activePage) // print state variable inside useEffect.
}, [activePage]);

wangdev87
  • 8,611
  • 3
  • 8
  • 31