Y
Y
Yuri Romanov2019-03-05 07:38:02
React
Yuri Romanov, 2019-03-05 07:38:02

React hooks. How to call a function with updated state?

Here is an example code:

function App() {
  const [count, setCount] = useState(0);

  const printCount = () =>{
    console.log(count);
  };

  const incCount = () => {
    setCount(count + 1);
    printCount();
  };

  return (
    <div className="App">
      <button onClick={() => { incCount(); }}>Inc count</button>
      <div>{count}</div>
    </div>
  );
}

When you click on the "Inc count" button, the incCount method is called in which the count value is increased and then the printCount method is immediately called, which displays the count value to the console. So, when you clicked, the value of count increased and became equal to "1", but the value "0" is displayed in the console, that is, the old value. As if the incCount and printCount methods work asynchronously and incCount does not have time to change the value before calling printCount. How to call several methods in a row and at the same time be sure that they will work with the updated state?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrey Okhotnikov, 2019-03-05
@darteil

To do this, useEffect is used in this case, the function will be called every time the count changes, and you can already add anything to it, similar to how the callback works in setState

M
Medin K, 2019-03-05
@medin84

it just happened

export default function App() {
  let [count, setCount] = useState(0); // const >>> let

  const printCount = () =>{
    console.log(count);
  };

  const incCount = () => {
    count++; ///////////////////////// increment
    setCount(count); /////////////// set
    printCount();
  };

  return (
    <div className="App">
      <button onClick={() => { incCount(); }}>Inc count</button>
      <div>{count}</div>
    </div>
  );
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question