Accessing new state of a variable in the same function

I have a simple React function here but it doesn’t work as I want. Here’s the code

 function handleClick() {
    setTwo(num * 2);

I want to update variables one and two but I manage to do it only with two and the second variable one is working on the basis of the previous value of the variable two but I need it to work with the new updated value of two. Can anyone help ?
*I’ve tried with useEffect but it instantly changes the value on the first render

Would need to see more code as it’s unclear what you’re trying to do

export default function PageNum({ num, setOne, setTwo, pagesLimit, two }) {
  function handleClick() {
    setTwo(num * pagesLimit);
    setOne(two - num);

  return (
    <li onClick={handleClick}>
      <a href="#" role="button">

This is a component that is a button on a pagination section. The items that are showing on the screen are set by the functionality that does array.split(one,two) on the array of all items. So when the button is clicked, I wanted to display the page that has the same number that the button has. In this function, I want to set new value to two variable and then, based on that new variable I want to set variable one to (two-pagesLimit) but when the function runs, it works with the old value of two and not the one that had just been updated in the line above. In other words, I want setOne to work with the value of two that has just been updated in the line above.

function handleClick() {
  const n = num * pagesLimit;
  setOne(two - n);
1 Like

I’ve just tried that and I got the same result

The two handleClick functions are different, so I don’t know which one you want to do. It’s just a JS function though, so if you want two to be one number, then one to be that number minus something then you just calculate what two should be and then set one and two accordingly :man_shrugging:t3:

1 Like

Thank you! With your help I managed to figure it out and see where I was wrong :smile:

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.