Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

How to use `setState` callback on react hooks

React hooks introduces useState for setting component state. But how can I use hooks to replace the callback like the below code:
setState(
{ name: "Michael" },
() => console.log(this.state)
);

I want to do something after the state is updated.

I know I can use useEffect to do the extra things but I have to check the state previous value which requires a bit code. I am looking for a simple solution that can be used with useState hook.
by

2 Answers

espadacoder11

const [counter, setCounter] = useState(0);

const doSomething = () => {
setCounter(123);
}

useEffect(() => {
console.log('Do something after counter has changed', counter);
}, [counter]);
sandhya6gczb
Wrapping setState in a promise allows to trigger an arbitrary action after completion:

import React, {useState} from 'react'

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

function handleClick(){
Promise.resolve()
.then(() => { setCount(count => count+1)})
.then(() => console.log(count))
}


return (
<button onClick= {handleClick}> Increase counter </button>
)
}
export default App;

Login / Signup to Answer the Question.