Answer the question
In order to leave comments, you need to log in
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>
);
}
Answer the question
In order to leave comments, you need to log in
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
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 questionAsk a Question
731 491 924 answers to any question